Skip to content

Commit

Permalink
feat: using new transform and bundle task framework
Browse files Browse the repository at this point in the history
  • Loading branch information
XGHeaven committed Nov 19, 2024
1 parent 073a6cb commit b2b81df
Show file tree
Hide file tree
Showing 27 changed files with 714 additions and 1,246 deletions.
5 changes: 5 additions & 0 deletions .changeset/gold-jeans-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ice/pkg': major
---

feat: using new transform and bundle task framework
2 changes: 1 addition & 1 deletion examples/react-component/build.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default defineConfig({
['@ice/pkg-plugin-jsx-plus'],
],
transform: {
formats: ['esm', 'es2017', 'cjs'],
formats: ['cjs', 'esm', 'es2017'],
},
jsxRuntime: 'classic',
sourceMaps: false,
Expand Down
1 change: 0 additions & 1 deletion packages/pkg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
"@rollup/plugin-replace": "^6.0.0",
"@rollup/pluginutils": "^5.0.5",
"@swc/core": "1.7.40",
"acorn": "^8.10.0",
"autoprefixer": "^10.4.2",
"build-scripts": "^2.0.0",
"cac": "^6.7.12",
Expand Down
12 changes: 12 additions & 0 deletions packages/pkg/src/helpers/deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { loadPkg } from './load.js';
import consola from 'consola';

const pkg = loadPkg(process.cwd());

export function checkDependencyExists(dependency: string, link: string) {
if (!pkg?.dependencies?.[dependency]) {
consola.error(`当前组件/库依赖 \`${dependency}\`, 请运行命令 \`npm i ${dependency} --save\` 安装此依赖。更多详情请看 \`${link}\``);
process.exit(1);
}
return pkg?.dependencies?.[dependency];
}
21 changes: 21 additions & 0 deletions packages/pkg/src/helpers/filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createFilter } from '@rollup/pluginutils';

/**
* default include src/**.m?[jt]sx? but exclude .d.ts file
*
* @param extraInclude include other file types
* @param extraExclude exclude other file types
*
* @example exclude node_modules createScriptsFilter([], [/node_modules/])
*/
export const createScriptsFilter = (
extraIncludes: RegExp[] = [],
extraExcludes: RegExp[] = [],
) => {
// Match non node_modules files. In ICEPKG V2, we only compile src/**.m?[jt]sx? files.
const includes = [/^(?!.*node_modules\/).*\.(?:[cm]?[jt]s|[jt]sx)$/].concat(extraIncludes);

const notCompiledDeps = ['core-js', 'core-js-pure', 'tslib', '@swc/helpers', '@babel/runtime', 'babel-runtime'];
const excludes = [/\.d\.ts$/, new RegExp(`node_modules/(${notCompiledDeps.join('|')})`)].concat(extraExcludes);
return createFilter(includes, excludes);
};
2 changes: 1 addition & 1 deletion packages/pkg/src/helpers/getBabelOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TransformOptions } from '@babel/core';
import { BabelPluginOptions } from 'src/rollupPlugins/babel.js';
import { JSX_RUNTIME_SOURCE } from '../constants.js';
import { BabelPluginOptions } from '../transformers/babel.js';

function getBabelOptions(
plugins: babel.PluginItem[],
Expand Down
186 changes: 86 additions & 100 deletions packages/pkg/src/helpers/getRollupOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,12 @@ import styles from 'rollup-plugin-styler';
import autoprefixer from 'autoprefixer';
import PostcssPluginRpxToVw from 'postcss-plugin-rpx2vw';
import json from '@rollup/plugin-json';
import swcPlugin from '../rollupPlugins/swc.js';
import minifyPlugin from '../rollupPlugins/minify.js';
import babelPlugin from '../rollupPlugins/babel.js';
import { builtinNodeModules } from './builtinModules.js';
import image from '@rollup/plugin-image';
import { visualizer } from 'rollup-plugin-visualizer';
import replace from '@rollup/plugin-replace';
import getDefaultDefineValues from './getDefaultDefineValues.js';
import transformAliasPlugin from '../rollupPlugins/alias.js';
import bundleAliasPlugin from '@rollup/plugin-alias';

import {
Context,
TaskName,
Expand All @@ -30,6 +25,7 @@ import type {
Plugin,
} from 'rollup';
import path from 'path';
import { transformerPlugin } from '../rollupPlugins/transformer.js';

interface PkgJson {
name: string;
Expand All @@ -44,106 +40,96 @@ export function getRollupOptions(
taskRunnerContext: TaskRunnerContext,
) {
const { pkg, commandArgs, command, rootDir } = context;
const { name: taskName, config: taskConfig } = taskRunnerContext.buildTask;
const { name: taskName, config: _taskConfig } = taskRunnerContext.buildTask;
// TODO: assert is BundleTaskConfig
const taskConfig = _taskConfig as BundleTaskConfig
const rollupOptions: RollupOptions = {};
const plugins: Plugin[] = [];

if (taskConfig.babelPlugins?.length) {
plugins.push(
babelPlugin(
taskConfig.babelPlugins,
{
jsxRuntime: taskConfig.jsxRuntime,
pragma: taskConfig?.swcCompileOptions?.jsc?.transform?.react?.pragma,
pragmaFrag: taskConfig?.swcCompileOptions?.jsc?.transform?.react?.pragmaFrag,
},
taskConfig.type === 'bundle' && taskConfig.compileDependencies,
taskConfig.modifyBabelOptions,
),
);
}
plugins.push(
swcPlugin(
taskConfig.jsxRuntime,
const alias = {};
Object.keys(taskConfig.alias).forEach((key) => {
// Add full path for relative path alias
alias[key] = taskConfig.alias[key].startsWith('.') ? path.resolve(rootDir, taskConfig.alias[key]) : taskConfig.alias[key];
});

const plugins: Plugin[] = [
transformerPlugin({
transformers: [],
alias,
babelPlugins: taskConfig.babelPlugins,
babelOptions: {
jsxRuntime: taskConfig.jsxRuntime,
pragma: taskConfig?.swcCompileOptions?.jsc?.transform?.react?.pragma,
pragmaFrag: taskConfig?.swcCompileOptions?.jsc?.transform?.react?.pragmaFrag,
},
compileDependencies: taskConfig.compileDependencies,
modifyBabelOptions: taskConfig.modifyBabelOptions,
jsxRuntime: taskConfig.jsxRuntime,
rootDir,
taskConfig.swcCompileOptions,
taskConfig.type === 'bundle' && taskConfig.compileDependencies,
),
);

if (taskConfig.type === 'transform') {
plugins.push(transformAliasPlugin(rootDir, taskConfig.alias));
} else if (taskConfig.type === 'bundle') {
const [external, globals] = getExternalsAndGlobals(taskConfig, pkg as PkgJson);
rollupOptions.input = taskConfig.entry;
rollupOptions.external = external;
rollupOptions.output = getRollupOutputs({
globals,
bundleTaskConfig: taskConfig,
pkg: pkg as PkgJson,
esVersion: taskName === TaskName.BUNDLE_ES2017 ? 'es2017' : 'es5',
mode: taskRunnerContext.mode,
command,
});
extraSwcOptions: taskConfig.swcCompileOptions,
}),
];

const cssMinify = taskConfig.cssMinify(taskRunnerContext.mode, command);
const defaultStylesOptions: StylesRollupPluginOptions = {
plugins: [
autoprefixer(),
PostcssPluginRpxToVw,
const [external, globals] = getExternalsAndGlobals(taskConfig, pkg as PkgJson);
rollupOptions.input = taskConfig.entry;
rollupOptions.external = external;
rollupOptions.output = getRollupOutputs({
globals,
bundleTaskConfig: taskConfig,
pkg: pkg as PkgJson,
esVersion: taskName === TaskName.BUNDLE_ES2017 ? 'es2017' : 'es5',
mode: taskRunnerContext.mode,
command,
});

const cssMinify = taskConfig.cssMinify(taskRunnerContext.mode, command);
const defaultStylesOptions: StylesRollupPluginOptions = {
plugins: [
autoprefixer(),
PostcssPluginRpxToVw,
],
mode: 'extract',
autoModules: true,
minimize: typeof cssMinify === 'boolean' ? cssMinify : cssMinify.options,
sourceMap: taskConfig.sourcemap,
};
plugins.push(
replace({
values: {
...getDefaultDefineValues(taskRunnerContext.mode),
// User define can override above.
...taskConfig.define,
},
preventAssignment: true,
}),
styles((taskConfig.modifyStylesOptions ?? [((options) => options)]).reduce(
(prevStylesOptions, modifyStylesOptions) => modifyStylesOptions(prevStylesOptions),
defaultStylesOptions,
)),
image(),
json(),
nodeResolve({ // To locates modules using the node resolution algorithm.
extensions: [
'.mjs', '.js', '.json', '.node', // plugin-node-resolve default extensions
'.ts', '.jsx', '.tsx', '.mts', '.cjs', '.cts', // @ice/pkg default extensions
...(taskConfig.extensions || []),
],
mode: 'extract',
autoModules: true,
minimize: typeof cssMinify === 'boolean' ? cssMinify : cssMinify.options,
sourceMap: taskConfig.sourcemap,
};
const alias = {};
Object.keys(taskConfig.alias).forEach((key) => {
// Add full path for relative path alias
alias[key] = taskConfig.alias[key].startsWith('.') ? path.resolve(rootDir, taskConfig.alias[key]) : taskConfig.alias[key];
});
plugins.push(
replace({
values: {
...getDefaultDefineValues(taskRunnerContext.mode),
// User define can override above.
...taskConfig.define,
},
preventAssignment: true,
}),
styles((taskConfig.modifyStylesOptions ?? [((options) => options)]).reduce(
(prevStylesOptions, modifyStylesOptions) => modifyStylesOptions(prevStylesOptions),
defaultStylesOptions,
)),
image(),
json(),
nodeResolve({ // To locates modules using the node resolution algorithm.
extensions: [
'.mjs', '.js', '.json', '.node', // plugin-node-resolve default extensions
'.ts', '.jsx', '.tsx', '.mts', '.cjs', '.cts', // @ice/pkg default extensions
...(taskConfig.extensions || []),
],
browser: taskConfig.browser,
}),
commonjs({ // To convert commonjs to import, make it compatible with rollup to bundle
extensions: [
'.js', // plugin-commonjs default extensions
'.jsx', '.ts', '.tsx',
...(taskConfig.extensions || []),
],
transformMixedEsModules: true,
}),
bundleAliasPlugin({
entries: alias,
}),
);
if (commandArgs.analyzer) {
plugins.push(visualizer({
title: `Rollup Visualizer(${taskName})`,
open: true,
filename: `${taskName}-stats.html`,
}));
}
browser: taskConfig.browser,
}),
commonjs({ // To convert commonjs to import, make it compatible with rollup to bundle
extensions: [
'.js', // plugin-commonjs default extensions
'.jsx', '.ts', '.tsx',
...(taskConfig.extensions || []),
],
transformMixedEsModules: true,
}),
);
if (commandArgs.analyzer) {
plugins.push(visualizer({
title: `Rollup Visualizer(${taskName})`,
open: true,
filename: `${taskName}-stats.html`,
}));
}

rollupOptions.plugins = plugins;
Expand Down
8 changes: 4 additions & 4 deletions packages/pkg/src/helpers/getTaskIO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ function getEntryId(entry: string): string {
return entry.split('/').pop().split('.').shift();
}

export const getTransformEntryDirs = (rootDir: string, entry: Record<string, string>) => {
export const getTransformEntryDirs = (rootDir: string, entry: Record<string, string>): string[] => {
const entries = Object.values(entry);
const transformEntryDirs: string[] = [];
const transformEntryDirs = new Set<string>()

entries.forEach((entryItem) => {
const absoluteEntry = isAbsolute(entryItem) ? entryItem : resolve(rootDir, entryItem);
transformEntryDirs.push(join(absoluteEntry, '..'));
transformEntryDirs.add(join(absoluteEntry, '..'));
});

return transformEntryDirs;
return Array.from(transformEntryDirs);
};

export const getTransformDefaultOutputDir = (rootDir: string, taskName: TaskValue) => {
Expand Down
Loading

0 comments on commit b2b81df

Please sign in to comment.