Skip to main content

Command Palette

Search for a command to run...

优化 webpack 4 配置加速 ci 构建过程

Updated
3 min read
优化 webpack 4 配置加速 ci 构建过程

如果你的项目里也同时包含了 js 和 ts 的代码,相信构建速度会是项目中一个让人头疼的问题。下面我会尝试给出一些提高构建速度的配置并给出说明。

毫无疑问,配置大部分是针对 rules的。

以下给出的配置都假设你的 webpack.config.js位于项目根目录下。

## optimization 部分

// 使用 terser 代替 uglify-js
const TerserPlugin = require('terser-webpack-plugin');
const isWsl = require('is-wsl');

// optimization
{
  // Keep the runtime chunk separated to enable long term caching
    // https://webpack.js.org/configuration/optimization/#optimizationruntimechunk
    runtimeChunk: true,

minimizer: [
    new TerserPlugin({
           terserOptions: {
               parse: {
                   // we want uglify-js to parse ecma 8 code. However, we don't want it
                   // to apply any minfication steps that turns valid ecma 5 code
                   // into invalid ecma 5 code. This is why the 'compress' and 'output'
                   // sections only apply transformations that are ecma 5 safe
                   // https://github.com/facebook/create-react-app/pull/4234
                   ecma: 8,
               },
               compress: {
                   ecma: 5,
                   warnings: false,
                   // Disabled because of an issue with Uglify breaking seemingly valid code:
                   // https://github.com/facebook/create-react-app/issues/2376
                   // Pending further investigation:
                   // https://github.com/mishoo/UglifyJS2/issues/2011
                   comparisons: false,
                   // Pending futher investigation:
                   // https://github.com/terser-js/terser/issues/120
                   inline: 2,
               },
               mangle: {
                   safari10: true,
               },
               output: {
                   ecma: 5,
                   comments: false,
                   // Turned on because emoji and regex is not minified properly using default
                   // https://github.com/facebook/create-react-app/issues/2488
                   ascii_only: true,
               },
           },

// Use multi-process parallel running to improve the build speed
           // Default number of concurrent runs: os.cpus().length - 1
           // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
           parallel: !isWsl,
           // Enable file caching
           cache: true,
           sourceMap: false,
           exclude: /\.min\.js$/,
       }),
  ]
}

## 针对 js(x) 文件的配置

rules

{
    test: /\.(js|jsx|mjs)$/,
    exclude: [/[/\\\\]node_modules[/\\\\]/],
    use: [
        'thread-loader',
        {
            loader: require.resolve('babel-loader'),
            options: {
                compact: true,
                configFile: './.babelrc',
                // 对项目 js 代码 transpile 的结果进行持久化缓存
                cacheDirectory: '.cache/babel',
                // 缓存文件不做 gzip 压缩,
                //当你的代码文件数量比较多时建议配置此项为 false
                cacheCompression: false,
            },
        },
        {
            loader: require.resolve('eslint-loader'),
            options: {
        // 对 lint 的结果进行缓存
                cache: '.cache/eslint',
            },
        },
    ],
},

plugins

// 再另一个进程里进行对 ts 的类型检查
new ForkTsCheckerWebpackPlugin({
    tsconfig: './tsconfig.json',
    // block webpack's emit to wait for type checker/linter and to add errors to the webpack's compilation
    // also required for the the overlay functionality of webpack-dev-server
    async: false,
    // checkSyntacticErrors is required as we use happyPackMode and the thread-loader to parallelise the builds
    checkSyntacticErrors: true,
}),

## 针对 ts(x) 文件的配置

const ForkTsCheckerWebpackPlugin = require(‘fork-ts-checker-webpack-plugin’);

const os = require(‘os’)
const cpus = os.cpus().length
// 需要给 fork-ts-checker-webpack-plugin 分配 1 个
const tsLoaderWorkers = cpus > 2 ? cpus — 1 : 1

rules

{
    test: /\.(tsx?|d.ts)$/,
    include: 'src',
    use: [
        {
            // 启用基于文件的缓存
            loader: require.resolve('cache-loader'),
            options: {
                cacheDirectory: '.cache/cache-loader',
            },
        },
        {
            loader: require.resolve('thread-loader'),
            options: {
                workers: tsLoaderWorkers,
            },
        },
        {
            loader: require.resolve('ts-loader'),
            options: {
       /**
        * Increase build speed by disabling typechecking for the
        * main process and is required to be used with thread-loader
        * [@see](http://twitter.com/see) [https://github.com/TypeStrong/ts-loader/blob/master/examples/thread-loader/webpack.config.js](https://github.com/TypeStrong/ts-loader/blob/master/examples/thread-loader/webpack.config.js)
        * Requires to use the ForkTsCheckerWebpack Plugin
        */
                happyPackMode: true,
                configFile: `./tsconfig.json`,
            },
        },
    ],
},

plugins

// 在另一个进程里进行对 ts 的类型检查
new ForkTsCheckerWebpackPlugin({
    tsconfig: './tsconfig.json',
    // block webpack's emit to wait for type checker/linter and to add errors to the webpack's compilation
    // also required for the the overlay functionality of webpack-dev-server
    async: false,
    // checkSyntacticErrors is required as we use happyPackMode and the thread-loader to parallelise the builds
    checkSyntacticErrors: true,
}),

## 效果

当前项目代码量当前项目代码量

108 views

More from this blog

Al's blog

21 posts