webpack.base.babel.js 18.9 KB
Newer Older
1
const { deepmerge, createDebug, winPath, resolve } = require('@umijs/utils');
邓晓峰's avatar
邓晓峰 committed
2
const { ESBuildPlugin, ESBuildMinifyPlugin } = require('esbuild-loader');
3
const fs = require('fs');
dengxiaofeng's avatar
dengxiaofeng committed
4 5
const path = require('path');
const webpack = require('webpack');
6
const Config = require('webpack-chain');
邓晓峰's avatar
邓晓峰 committed
7
const lodash = require('lodash');
邓晓峰's avatar
邓晓峰 committed
8
const { getTargetsAndBrowsersList, getBabelPresetOpts, getBabelOpts } = require('@umijs/bundler-utils');
邓晓峰's avatar
邓晓峰 committed
9 10 11
const { join } = require('lodash');
const terserOptions = require('./terserOptions');
const { css, createCSSRule } = require('./css');
邓晓峰's avatar
邓晓峰 committed
12
const pkg = require('../../package.json');
邓晓峰's avatar
邓晓峰 committed
13
const ASSET_PATH = process.env.ASSET_PATH || '/';
邓晓峰's avatar
邓晓峰 committed
14
const { ThemeColorReplacer, themePluginOption } = require('../../config/plugin.config');
15 16 17
let defineConfig = require('../../config/config');
const resolveDefine = require('./resolveDefine');
const { getPkgPath, shouldTransform } = require('./pkgMatch');
邓晓峰's avatar
邓晓峰 committed
18
const { TYPE_ALL_EXCLUDE, isMatch, excludeToPkgs, es5ImcompatibleVersionsToPkg } = require('./nodeModulesTransform');
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

function getUserLibDir({ library }) {
  if (
    (pkg.dependencies && pkg.dependencies[library]) ||
    (pkg.devDependencies && pkg.devDependencies[library]) ||
    // egg project using `clientDependencies` in ali tnpm
    (pkg.clientDependencies && pkg.clientDependencies[library])
  ) {
    return winPath(
      path.dirname(
        // 通过 resolve 往上找,可支持 lerna 仓库
        // lerna 仓库如果用 yarn workspace 的依赖不一定在 node_modules,可能被提到根目录,并且没有 link
        resolve.sync(`${library}/package.json`, {
          basedir: process.cwd(),
        }),
      ),
    );
  }
  return null;
}
const defaultConfig = {
  autoprefixer: {
    flexbox: 'no-2009',
  },
  cssnano: { mergeRules: false, minifyFontValues: { removeQuotes: false } },
  nodeModulesTransform: {
    type: 'all',
    exclude: [],
  },
邓晓峰's avatar
邓晓峰 committed
48
  hash: true,
49 50 51 52 53 54 55 56
  targets: {
    node: true,
    chrome: 49,
    firefox: 64,
    safari: 10,
    edge: 13,
    ios: 10,
    ie: 11,
邓晓峰's avatar
邓晓峰 committed
57
  },
58 59 60 61 62
};
module.exports = options => {
  const chainConfig = new Config();
  chainConfig.mode(options.mode);
  defineConfig = Object.assign(defineConfig, defaultConfig);
邓晓峰's avatar
邓晓峰 committed
63
  const { env } = process;
64 65 66 67
  const isDev = process.env.NODE_ENV === 'development';
  const isProd = process.env.NODE_ENV === 'production';
  const disableCompress = process.env.COMPRESS === 'none';
  const isWebpack5 = webpack.version.startsWith('5');
68
  const cwd = process.cwd();
69 70
  const devtool = options.devtool || false;

邓晓峰's avatar
邓晓峰 committed
71
  chainConfig.devtool(isDev ? (devtool === false ? false : devtool || 'cheap-module-source-map') : devtool);
邓晓峰's avatar
邓晓峰 committed
72
  const { mfsu } = defineConfig;
73
  const useHash = defineConfig.hash && isProd;
邓晓峰's avatar
邓晓峰 committed
74

75
  const absOutputPath = process.env.npm_config_releasepath
邓晓峰's avatar
邓晓峰 committed
76
    ? path.resolve(process.env.npm_config_releasepath, pkg.name.toLocaleLowerCase())
77 78 79 80 81
    : path.resolve(process.cwd(), pkg.name.toLocaleLowerCase());

  chainConfig.output
    .path(absOutputPath)
    .filename(useHash ? `[name].[contenthash:8].js` : `[name].js`)
邓晓峰's avatar
邓晓峰 committed
82
    .chunkFilename(useHash ? `[name].[contenthash:8].async.js` : `[name].js`)
83
    .publicPath(`/${pkg.name.toLocaleLowerCase()}/`)
邓晓峰's avatar
邓晓峰 committed
84
    // .futureEmitAssets(true)
85 86 87
    .crossOriginLoading('anonymous')
    .pathinfo(isDev || disableCompress);

邓晓峰's avatar
邓晓峰 committed
88 89 90 91
  if (!isWebpack5) {
    chainConfig.output.futureEmitAssets(true);
  }
  if (isWebpack5) {
邓晓峰's avatar
邓晓峰 committed
92 93 94
    chainConfig.cache({
      type: 'filesystem',
      buildDependencies: {
邓晓峰's avatar
邓晓峰 committed
95
        config: [__filename, path.join(process.cwd(), 'package.json')],
邓晓峰's avatar
邓晓峰 committed
96
      },
邓晓峰's avatar
邓晓峰 committed
97 98 99 100
      cacheDirectory: path.resolve(process.cwd(), 'node_modules/.cache'),
      compression: 'gzip',
      version: `${process.env.GIT_REV}`,
    });
邓晓峰's avatar
邓晓峰 committed
101
  }
102 103 104 105
  chainConfig.resolve.modules
    .add('node_modules')
    .add('src')
    .end()
邓晓峰's avatar
邓晓峰 committed
106
    .extensions.merge([
邓晓峰's avatar
邓晓峰 committed
107 108 109
      '.js',
      '.jsx',
      '.react.js',
邓晓峰's avatar
邓晓峰 committed
110 111 112 113 114 115 116 117 118 119
      '.web.js',
      '.wasm',
      '.mjs',
      '.js',
      '.web.jsx',
      '.jsx',
      '.web.ts',
      '.ts',
      '.web.tsx',
      '.tsx',
邓晓峰's avatar
邓晓峰 committed
120
      '.json',
邓晓峰's avatar
邓晓峰 committed
121
    ])
122 123 124 125
    .end()
    .mainFields.merge(['browser', 'jsnext:main', 'main']);

  const libraries = [
dengxiaofeng's avatar
dengxiaofeng committed
126
    {
127 128
      name: 'react',
      path: path.dirname(require.resolve(`react/package.json`)),
dengxiaofeng's avatar
dengxiaofeng committed
129
    },
130 131 132 133 134 135 136
    {
      name: 'react-dom',
      path: path.dirname(require.resolve(`react-dom/package.json`)),
    },
  ];

  libraries.forEach(library => {
邓晓峰's avatar
邓晓峰 committed
137
    chainConfig.resolve.alias.set(library.name, getUserLibDir({ library: library.name }) || library.path);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  });

  chainConfig.resolve.alias.set('@', path.join(__dirname, '../../', 'src'));

  if (defineConfig.alias) {
    Object.keys(defineConfig.alias).forEach(key => {
      chainConfig.resolve.alias.set(key, defineConfig.alias[key]);
    });
  }

  chainConfig.target('web');

  const { targets, browserslist } = getTargetsAndBrowsersList({
    config: defineConfig,
    type: 'csr',
  });

邓晓峰's avatar
邓晓峰 committed
155
  const presetOpts = getBabelPresetOpts({
156 157
    config: defineConfig,
    env: process.env.NODE_ENV,
邓晓峰's avatar
邓晓峰 committed
158
    targets,
159 160
  });

邓晓峰's avatar
邓晓峰 committed
161
  // eslint-disable-next-line global-require
邓晓峰's avatar
邓晓峰 committed
162
  const preset = require('./babel-preset');
163 164 165 166 167 168 169 170 171 172 173 174 175
  const getPreset = preset({
    ...presetOpts,
    env: {
      useBuiltIns: 'entry',
      corejs: 3,
      modules: false,
    },
    react: {
      development: isDev,
    },
    reactRemovePropTypes: isProd,
    reactRequire: true,
    lockCoreJS3: {},
邓晓峰's avatar
邓晓峰 committed
176
    import: (presetOpts.import || []).concat([{ libraryName: 'antd', libraryDirectory: 'es', style: true }]),
177
  });
178

邓晓峰's avatar
邓晓峰 committed
179
  const babelOpts = {
180 181 182
    sourceType: 'unambiguous',
    babelrc: false,
    presets: [...getPreset.presets, ...(defineConfig.extraBabelPresets || [])],
邓晓峰's avatar
邓晓峰 committed
183
    plugins: [...getPreset.plugins, ...(defineConfig.extraBabelPlugins || [])].filter(Boolean),
184
    env: getPreset.env,
邓晓峰's avatar
邓晓峰 committed
185
    compact: false,
186 187 188 189 190
  };

  chainConfig.module
    .rule('js')
    .test(/\.(js|mjs|jsx|ts|tsx)$/)
邓晓峰's avatar
邓晓峰 committed
191
    .include.add([cwd, ...(process.env.APP_ROOT ? [process.cwd()] : [])])
邓晓峰's avatar
邓晓峰 committed
192 193 194
    .end()
    .exclude.add(/node_modules/)
    .add(/\.mfsu/)
195 196
    .end()
    .use('babel-loader')
197
    .loader(require.resolve('@umijs/deps/compiled/babel-loader'))
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    .options(babelOpts);

  if (defineConfig.extraBabelIncludes) {
    defineConfig.extraBabelIncludes.forEach((include, index) => {
      const rule = `extraBabelInclude_${index}`;
      chainConfig.module
        .rule(rule)
        .test(/\.(js|mjs|jsx)$/)
        .include.add(a => {
          if (path.isAbsolute(include)) {
            return path.isAbsolute(include);
          }
          if (!a.includes('node_modules')) return false;
          const pkgPath = getPkgPath(a);
          return shouldTransform(pkgPath, include);
        })
        .end()
        .use('babel-loader')
        .loader(require.resolve('babel-loader'))
        .options(babelOpts);
    });
  }

221 222
  const staticDir = mfsu ? 'mf-static' : 'static';

223 224 225 226 227 228 229
  chainConfig.module
    .rule('images')
    .test(/\.(png|jpe?g|gif|webp|ico)(\?.*)?$/)
    .use('url-loader')
    .loader(require.resolve('url-loader'))
    .options({
      limit: defineConfig.inlineLimit || 10000,
230
      name: `${staticDir}/[name].[hash:8].[ext]`,
231 232 233 234 235
      // require 图片的时候不用加 .default
      esModule: false,
      fallback: {
        loader: require.resolve('file-loader'),
        options: {
236
          name: `${staticDir}/[name].[hash:8].[ext]`,
237
          esModule: false,
dengxiaofeng's avatar
dengxiaofeng committed
238 239
        },
      },
240
    });
邓晓峰's avatar
邓晓峰 committed
241

242 243 244 245
  chainConfig.module
    .rule('avif')
    .test(/\.(avif)(\?.*)?$/)
    .use('file-loader')
邓晓峰's avatar
邓晓峰 committed
246 247 248 249 250
    .loader(require.resolve('file-loader'))
    .options({
      name: `${staticDir}/[name].[hash:8].[ext]`,
      esModule: false,
    });
251

252 253 254 255
  chainConfig.module
    .rule('svg')
    .test(/\.(svg)(\?.*)?$/)
    .use('file-loader')
邓晓峰's avatar
邓晓峰 committed
256
    .loader(require.resolve('@umijs/deps/compiled/file-loader'))
257
    .options({
258
      name: `${staticDir}/[name].[hash:8].[ext]`,
259 260 261 262 263 264 265 266 267 268
      esModule: false,
    })
    .end();

  chainConfig.module
    .rule('fonts')
    .test(/\.(eot|woff|woff2|ttf)(\?.*)?$/)
    .use('file-loader')
    .loader(require.resolve('file-loader'))
    .options({
269
      name: `${staticDir}/[name].[hash:8].[ext]`,
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      esModule: false,
    });

  chainConfig.module
    .rule('mdeia')
    .test(/\.(mp4|webm)$/)
    .use('url-loader')
    .loader(require.resolve('url-loader'))
    .options({
      limit: 10000,
      outputPath: 'static',
    });

  chainConfig.module
    .rule('plaintext')
    .test(/\.(txt|text|md)$/)
    .use('raw-loader')
    .loader(require.resolve('raw-loader'));

邓晓峰's avatar
邓晓峰 committed
289
  if (defineConfig.workerLoader) {
290 291 292 293
    chainConfig.module
      .rule('worker')
      .test(/.*worker.(ts|js)/)
      .use('worker-loader')
邓晓峰's avatar
邓晓峰 committed
294 295 296
      .loader(require.resolve('@umijs/deps/compiled/worker-loader'))
      .options(defineConfig.workerLoader);
  }
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311
  css({
    type: 'csr',
    config: defineConfig,
    webpackConfig: chainConfig,
    isDev,
    disableCompress,
    browserslist,
    miniCSSExtractPluginPath: '',
    miniCSSExtractPluginLoaderPath: '',
  });

  if (defineConfig.externals) {
    chainConfig.externals(defineConfig.externals);
  }
邓晓峰's avatar
邓晓峰 committed
312
  if (!isWebpack5) {
邓晓峰's avatar
邓晓峰 committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326
    chainConfig.node.merge({
      setImmediate: false,
      module: 'empty',
      dns: 'mock',
      http2: 'empty',
      process: 'mock',
      dgram: 'empty',
      fs: 'empty',
      net: 'empty',
      tls: 'empty',
      child_process: 'empty',
      ...options.node,
    });
  }
327 328 329

  if (defineConfig.ignoreMomentLocale) {
    chainConfig.plugin('ignore-moment-locale').use(webpack.IgnorePlugin, [
dengxiaofeng's avatar
dengxiaofeng committed
330
      {
331 332
        resourceRegExp: /^\.\/locale$/,
        contextRegExp: /moment$/,
dengxiaofeng's avatar
dengxiaofeng committed
333
      },
334 335 336 337 338 339 340 341 342 343 344 345 346
    ]);
  }

  chainConfig.plugin('define').use(webpack.DefinePlugin, [
    resolveDefine({
      define: Object.assign(defineConfig.define || {}, {
        'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH),
        'process.env.MOCK': JSON.stringify(true),
        paths: {
          cwd: process.cwd(),
          absNodeModulesPath: path.join(process.cwd(), 'node_modules'),
          absSrcPath: path.join(process.cwd(), 'src'),
          absPagesPath: path.join(process.cwd(), 'src/pages'),
dengxiaofeng's avatar
dengxiaofeng committed
347
        },
348
      }),
dengxiaofeng's avatar
dengxiaofeng committed
349
    }),
350 351 352 353 354 355
  ]);

  const baseHtmlOptions = {
    inject: true,
    template: 'src/index.ejs',
    favicon: defineConfig.favicon ? defineConfig.favicon : false,
邓晓峰's avatar
邓晓峰 committed
356
    title: defineConfig.title && defineConfig.title !== false ? defineConfig.title : '',
357 358 359 360
    chunks: defaultConfig.chunks ? defaultConfig.chunks : 'all',
  };
  const htmlPluginOptions = isDev
    ? {
邓晓峰's avatar
邓晓峰 committed
361 362
      ...babelOpts,
    }
363
    : {
邓晓峰's avatar
邓晓峰 committed
364 365 366 367 368 369 370 371 372 373 374 375 376 377
      ...baseHtmlOptions,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    };
378

邓晓峰's avatar
邓晓峰 committed
379
  chainConfig.plugin('htmlPlugins').use(require.resolve('html-webpack-plugin'), [htmlPluginOptions]);
380

邓晓峰's avatar
邓晓峰 committed
381 382 383 384 385
  chainConfig.plugin('updateHtmlParams').use(require.resolve('./plugins/HtmlGenerator'), [
    {
      config: defineConfig,
    },
  ]);
386

邓晓峰's avatar
邓晓峰 committed
387
  chainConfig.plugin('replaceTheme').use(ThemeColorReplacer, [themePluginOption]);
388 389 390 391

  const copyPatterns = [
    fs.existsSync(path.join(process.cwd(), 'public')) && {
      from: path.join(cwd, 'public'),
邓晓峰's avatar
邓晓峰 committed
392
      to: path.resolve(process.env.npm_config_releasepath || process.cwd(), pkg.name.toLocaleLowerCase()),
393 394 395
    },
    ...(defineConfig.copy
      ? defineConfig.copy.map(item => {
邓晓峰's avatar
邓晓峰 committed
396
        if (typeof item === 'string') {
397
          return {
邓晓峰's avatar
邓晓峰 committed
398
            from: path.join(cwd, item),
邓晓峰's avatar
邓晓峰 committed
399
            to: path.resolve(process.env.npm_config_releasepath || process.cwd(), pkg.name.toLocaleLowerCase()),
400
          };
邓晓峰's avatar
邓晓峰 committed
401 402 403 404 405
        }
        return {
          from: path.join(cwd, item.from),
          to: path.resolve(
            process.env.npm_config_releasepath || process.cwd(),
邓晓峰's avatar
邓晓峰 committed
406
            `${pkg.name.toLocaleLowerCase()}/${item.to}`,
邓晓峰's avatar
邓晓峰 committed
407 408 409
          ),
        };
      })
410 411 412 413
      : []),
  ].filter(Boolean);

  if (copyPatterns.length) {
邓晓峰's avatar
邓晓峰 committed
414
    chainConfig.plugin('copy').use(require.resolve('copy-webpack-plugin'), [copyPatterns]);
415 416 417 418 419 420 421
  }

  if (isDev && defineConfig.fastRefresh) {
    const debug = createDebug('civ:preset-build-in:fastRefresh');
    chainConfig
      .plugin('fastRefresh')
      .after('hmr')
邓晓峰's avatar
邓晓峰 committed
422
      .use(require('@pmmmwh/react-refresh-webpack-plugin'), [{ overlay: false }]);
423 424 425 426 427 428 429 430 431
    debug('FastRefresh webpack loaded');
  }

  if (chainConfig.extraBabelIncludes) {
    chainConfig.extraBabelIncludes.forEach((include, index) => {
      const rule = `extraBabelInclude_${index}`;
      // prettier-ignore
      chainConfig.module
        .rule(rule)
邓晓峰's avatar
邓晓峰 committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
        .test(/\.(js|mjs|jsx)$/)
        .include
        .add((a) => {
          // 支持绝对路径匹配
          if (path.isAbsolute(include)) {
            return path.isAbsolute(include);
          }

          // 支持 node_modules 下的 npm 包
          if (!a.includes('node_modules')) return false;
          const pkgPath = getPkgPath(a);
          return shouldTransform(pkgPath, include);
        })
        .end()
        .use('babel-loader')
        .loader(require.resolve('babel-loader'))
        .options(babelOpts);
449 450 451 452 453 454 455 456 457 458 459 460
    });
  }

  chainConfig.module
    .rule('ts-in-node_modules')
    .test(/\.(jsx|ts|tsx)$/)
    .include.add(/node_modules/)
    .end()
    .use('babel-loader')
    .loader(require.resolve('babel-loader'))
    .options(babelOpts);

邓晓峰's avatar
邓晓峰 committed
461
  const rule = chainConfig.module.rule('js-in-node_modules').test(/\.(js|mjs)$/);
462 463 464 465 466 467
  const nodeModulesTransform = defineConfig.nodeModulesTransform || {
    type: 'all',
    exclude: [],
  };

  if (nodeModulesTransform.type === 'all') {
邓晓峰's avatar
邓晓峰 committed
468
    const exclude = lodash.uniq([...TYPE_ALL_EXCLUDE, ...(nodeModulesTransform.exclude || [])]);
469 470 471 472
    const pkgs = excludeToPkgs({ exclude });
    rule.include
      .add(/node_modules/)
      .end()
邓晓峰's avatar
邓晓峰 committed
473
      .exclude.add(path => isMatch({ path, pkgs }))
474 475 476 477 478 479 480
      .end();
  } else {
    const pkgs = {
      ...es5ImcompatibleVersionsToPkg(),
      ...excludeToPkgs({ exclude: nodeModulesTransform.exclude || [] }),
    };
    rule.include
邓晓峰's avatar
邓晓峰 committed
481 482
      .add(path =>
        isMatch({
483 484
          path,
          pkgs,
邓晓峰's avatar
邓晓峰 committed
485 486
        }),
      )
487 488 489 490 491 492
      .end();
  }


  if ((isProd && defineConfig.analyze) || process.env.ANALYZE) {
    const mergeAnalyze = Object.assign(
邓晓峰's avatar
邓晓峰 committed
493
      {
494 495 496 497 498 499 500
        analyzerMode: process.env.ANALYZE_MODE || 'server',
        analyzerPort: process.env.ANALYZE_PORT || 8888,
        openAnalyzer: process.env.ANALYZE_OPEN !== 'none',
        generateStatsFile: !!process.env.ANALYZE_DUMP,
        statsFilename: process.env.ANALYZE_DUMP || 'stats.json',
        logLevel: process.env.ANALYZE_LOG_LEVEL || 'info',
        defaultSizes: 'parsed', // stat  // gzip
邓晓峰's avatar
邓晓峰 committed
501
      },
502 503 504 505
      defineConfig.analyze,
    );
    chainConfig
      .plugin('bundle-analyzer')
邓晓峰's avatar
邓晓峰 committed
506
      .use(require('umi-webpack-bundle-analyzer').BundleAnalyzerPlugin, [mergeAnalyze || {}]);
507 508 509
  }

  if (process.env.PROGRESS !== 'none') {
510
    chainConfig.plugin('progress').use(require.resolve('webpackbar'), [
邓晓峰's avatar
邓晓峰 committed
511 512 513 514 515 516 517 518 519 520
      mfsu
        ? {
            name: 'MFSU',
            color: '#facc00',
          }
        : defineConfig.ssr
        ? {
            name: type === 'ssr' ? 'Server' : 'Client',
          }
        : {},
521
    ]);
522 523
  }

524 525 526 527 528 529 530 531 532
  // if (process.env.FRIENDLY_ERROR !== 'none') {
  //   chainConfig
  //     .plugin('friendly-error')
  //     .use(require.resolve('friendly-errors-webpack-plugin'), [
  //       {
  //         clearConsole: false,
  //       },
  //     ]);
  // }
533 534 535 536

  if (process.env.WEBPACK_PROFILE) {
    chainConfig.profile(true);
    const statsInclude = ['verbose', 'normal', 'minimal'];
邓晓峰's avatar
邓晓峰 committed
537
    chainConfig.stats(statsInclude.includes(process.env.WEBPACK_PROFILE) ? process.env.WEBPACK_PROFILE : 'verbose');
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
    const StatsPlugin = require('stats-webpack-plugin');
    chainConfig.plugin('stats-webpack-plugin').use(
      new StatsPlugin('stats.json', {
        chunkModules: true,
      }),
    );
  }

  chainConfig.when(
    isDev,
    chainConfig => {
      if (isDev) {
        chainConfig.plugin('hmr').use(webpack.HotModuleReplacementPlugin);
      }
    },
    chainConfig => {
      chainConfig.optimization.noEmitOnErrors(true);
      chainConfig.performance.hints(false);

      if (!isWebpack5) {
邓晓峰's avatar
邓晓峰 committed
558
        chainConfig.plugin('hash-module-ids').use(webpack.HashedModuleIdsPlugin, []);
559 560 561 562 563
      }

      if (disableCompress) {
        chainConfig.optimization.minimize(false);
      } else if (!options.__disableTerserForTest) {
邓晓峰's avatar
邓晓峰 committed
564 565 566 567 568 569 570 571 572
        chainConfig.optimization.minimizer('terser').use(require.resolve('terser-webpack-plugin'), [
          {
            terserOptions: deepmerge(terserOptions, defineConfig.terserOptions || {}),
            sourceMap: defineConfig.devtool !== false,
            cache: process.env.TERSER_CACHE !== 'none',
            parallel: true,
            extractComments: false,
          },
        ]);
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
      }
    },
  );

  function createCSSRuleFn(opts) {
    createCSSRule({
      webpackConfig: chainConfig,
      config: defineConfig,
      isDev,
      type: 'csr',
      browserslist,
      miniCSSExtractPluginLoaderPath: '',
      ...opts,
    });
  }

邓晓峰's avatar
邓晓峰 committed
589 590 591 592 593
  if (defineConfig.esbuild) {
    const { target = 'es2015' } = defineConfig.esbuild || {};
    const optsMap = {
      csr: {
        minify: true,
邓晓峰's avatar
邓晓峰 committed
594
        target,
邓晓峰's avatar
邓晓峰 committed
595 596 597 598 599
      },
    };
    const opt = optsMap.csr;
    chainConfig.optimization.minimize = true;
    chainConfig.optimization.minimizer = [new ESBuildMinifyPlugin(opt)];
邓晓峰's avatar
邓晓峰 committed
600
    chainConfig.plugin('es-build').use(new ESBuildPlugin());
邓晓峰's avatar
邓晓峰 committed
601
  }
602

603 604 605
  if (defineConfig.chainWebpack) {
    defineConfig.chainWebpack(chainConfig, {
      type: 'csr',
606
      // mfsu,
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
      env: process.env,
      webpack,
      createCSSRule: createCSSRuleFn,
    });
  }

  // if (defineConfig.chunks) {
  //   chainConfig
  //     .plugin('htmlPlugins')
  //     .use(require('html-webpack-plugin'))
  //     .tap(options => {
  //       options.chunks = defineConfig.chunks;
  //       return options;
  //     });
  // }

  let ret = chainConfig.toConfig();

  // speed-measure-webpack-plugin
  if (process.env.SPEED_MEASURE) {
    const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
    const smpOption =
      process.env.SPEED_MEASURE === 'CONSOLE'
        ? { outputFormat: 'human', outputTarget: console.log }
        : {
邓晓峰's avatar
邓晓峰 committed
632
          outputFormat: 'json',
邓晓峰's avatar
邓晓峰 committed
633
            outputTarget: join(process.cwd(), 'speed-measure.json'),
邓晓峰's avatar
邓晓峰 committed
634
        };
635 636 637 638
    const smp = new SpeedMeasurePlugin(smpOption);
    ret = smp.wrap(ret);
  }

邓晓峰's avatar
邓晓峰 committed
639
  const { entry } = options;
640 641 642 643
  if (defineConfig.runtimePublicPath) {
    entry.push(require.resolve('./runtimePublicPathEntry'));
  }

邓晓峰's avatar
邓晓峰 committed
644
  const nodeLibs = require('node-libs-browser');
645
  // const ProvidePlugin = webpack.ProvidePlugin;
邓晓峰's avatar
邓晓峰 committed
646
  if (isWebpack5) {
邓晓峰's avatar
邓晓峰 committed
647 648
    ret.plugins.push(
      new webpack.ProvidePlugin({
邓晓峰's avatar
邓晓峰 committed
649
        process: nodeLibs.process,
邓晓峰's avatar
邓晓峰 committed
650
      }),
邓晓峰's avatar
邓晓峰 committed
651 652 653 654
    );
    ret.resolve.fallback = {
      ...ret.resolve.fallback,
      ...Object.keys(nodeLibs).reduce((memo, key) => {
邓晓峰's avatar
邓晓峰 committed
655 656
        if (nodeLibs[key]) {
          memo[key] = nodeLibs[key];
邓晓峰's avatar
邓晓峰 committed
657
        } else {
邓晓峰's avatar
邓晓峰 committed
658 659 660
          memo[key] = false;
        }
        return memo;
邓晓峰's avatar
邓晓峰 committed
661 662 663
      }, {}),
      http: false,
      https: false,
邓晓峰's avatar
邓晓峰 committed
664
    };
邓晓峰's avatar
邓晓峰 committed
665
  }
666

667 668 669
  ret = {
    ...ret,
    // mode: options.mode,
邓晓峰's avatar
邓晓峰 committed
670
    entry,
671 672 673 674 675 676 677 678 679
    plugins: options.plugins.concat([...ret.plugins]),
    optimization: {
      ...options.optimization,
      ...ret.optimization,
    },
    performance: options.performance || {},
  };
  return ret;
};