Skip to content

Commit

Permalink
chore: use the same opts for bundler
Browse files Browse the repository at this point in the history
  • Loading branch information
Jinbao1001 committed Apr 29, 2024
1 parent ee06a22 commit e27a359
Show file tree
Hide file tree
Showing 4 changed files with 205 additions and 292 deletions.
185 changes: 181 additions & 4 deletions src/builder/bundle/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
import type { webpack } from '@umijs/bundler-webpack';
import type { DevTool } from '@umijs/bundler-webpack/compiled/webpack-5-chain';
import { chalk, importLazy, lodash, tryPaths } from '@umijs/utils';
import path from 'path';
import { getCachePath, logger } from '../../utils';
import type { BundleConfigProvider } from '../config';
import makoBundle from './mako';
import webpackBundle from './webpack';
import {
getBabelPresetReactOpts,
getBabelStyledComponentsOpts,
getBundleTargets,
} from '../utils';
process.env.OKAM = require.resolve(
'/Users/xiaoxiao/work/mako/packages/bundler-okam/index',
);

export interface IBundleWatcher {
close: () => void;
}

const bundler: typeof import('@umijs/bundler-webpack') = importLazy(
path.dirname(require.resolve('@umijs/bundler-webpack/package.json')),
);

const {
CSSMinifier,
JSMinifier,
}: typeof import('@umijs/bundler-webpack/dist/types') = importLazy(
require.resolve('@umijs/bundler-webpack/dist/types'),
);

const extensions = ['.js', '.jsx', '.ts', '.tsx', '.cjs', '.mjs'];

interface IBundleOpts {
cwd: string;
configProvider: BundleConfigProvider;
Expand All @@ -17,15 +40,169 @@ interface IBundleOpts {
function bundle(opts: Omit<IBundleOpts, 'watch'>): Promise<void>;
function bundle(opts: IBundleOpts): Promise<IBundleWatcher>;
async function bundle(opts: IBundleOpts): Promise<void | IBundleWatcher> {
const enableCache = process.env.FATHER_CACHE !== 'none';
const closeHandlers: webpack.Watching['close'][] = [];

for (let i = 0; i < opts.configProvider.configs.length; i += 1) {
const config = opts.configProvider.configs[i];
const { plugins: extraPostCSSPlugins, ...postcssLoader } =
config.postcssOptions || {};
const babelSCOpts = getBabelStyledComponentsOpts(opts.configProvider.pkg);
// workaround for combine continuous onBuildComplete log in watch mode
const logStatus = lodash.debounce(
() =>
logger.info(
`Bundle from ${chalk.yellow(config.entry)} to ${chalk.yellow(
path.join(config.output.path, config.output.filename),
)}`,
),
100,
{ leading: true, trailing: false },
);

// log for normal build
!opts.watch && logStatus();
const options = {
cwd: opts.cwd,
watch: opts.watch,
config: {
alias: config.alias,
autoprefixer: config.autoprefixer,
chainWebpack: config.chainWebpack,
define: config.define,
devtool: config.sourcemap && ('source-map' as DevTool),
externals: config.externals || {},
outputPath: config.output.path,

// postcss config
extraPostCSSPlugins,
postcssLoader,

...(config.extractCSS !== false ? {} : { styleLoader: {} }),

// less config
theme: config.theme,

// compatible with IE11 by default
targets: getBundleTargets(config),
jsMinifier: JSMinifier.terser,
cssMinifier: CSSMinifier.cssnano,
extraBabelIncludes: [/node_modules/],

// set cache parent directory, will join it with `bundler-webpack`
// ref: https://github.com/umijs/umi/blob/8dad8c5af0197cd62db11f4b4c85d6bc1db57db1/packages/bundler-webpack/src/build.ts#L32
cacheDirectoryPath: getCachePath(),
},
entry: {
[path.parse(config.output.filename).name]: path.join(
opts.cwd,
config.entry,
),
},
babelPreset: [
require.resolve('@umijs/babel-preset-umi'),
{
presetEnv: {
targets: getBundleTargets(config),
},
presetReact: getBabelPresetReactOpts(
opts.configProvider.pkg,
opts.cwd,
),
presetTypeScript: {},
pluginTransformRuntime: {},
pluginLockCoreJS: {},
pluginDynamicImportNode: false,
},
],
beforeBabelPlugins: [
require.resolve('babel-plugin-dynamic-import-node'),
...(babelSCOpts
? [[require.resolve('babel-plugin-styled-components'), babelSCOpts]]
: []),
],
extraBabelPresets: config.extraBabelPresets,
extraBabelPlugins: config.extraBabelPlugins,

// configure library related options
chainWebpack(memo: any) {
memo.output.libraryTarget('umd');

if (config?.name) {
memo.output.library(config.name);
}

// modify webpack target
if (config.platform === 'node') {
memo.target('node');
}

if (enableCache) {
// use father version as cache version
memo.merge({
cache: { version: require('../../../package.json').version },
});
}

// also bundle svg as asset, because father force disable svgr
const imgRule = memo.module.rule('asset').oneOf('image');
if (imgRule.get('test')) {
imgRule.test(
new RegExp(imgRule.get('test').source.replace(/(\|png)/, '$1|svg')),
);
}

// disable progress bar
memo.plugins.delete('progress-plugin');

// auto bump analyze port
/* istanbul ignore if -- @preserve */
if (process.env.ANALYZE) {
memo.plugin('webpack-bundle-analyzer').tap((args: any) => {
args[0].analyzerPort += i;

return args;
});
}

return memo;
},

// enable webpack persistent cache
...(enableCache
? {
cache: {
buildDependencies: opts.buildDependencies,
},
}
: {}),

// collect close handlers for watch mode
...(opts.watch
? {
onBuildComplete({ isFirstCompile, close }: any) {
if (isFirstCompile) closeHandlers.push(close);
// log for watch mode
else logStatus();
},
}
: {}),
disableCopy: true,
};
if (process.env.OKAM && config.bundler === 'mako') {
await makoBundle(opts, config);
require('@umijs/bundler-webpack/dist/requireHook');
const { build } = require(process.env.OKAM);

const entry = tryPaths(
extensions.map((ext) => path.join(opts.cwd, `${config.entry}${ext}`)),
) as string;
options.entry = {
[path.parse(config.output.filename).name]: entry,
};

await build(options);
} else {
await webpackBundle(opts, config, closeHandlers);
await bundler.build(options);
}
}

Expand Down
92 changes: 0 additions & 92 deletions src/builder/bundle/mako.ts

This file was deleted.

Loading

0 comments on commit e27a359

Please sign in to comment.