webpack4-优化

422 阅读1分钟

webpack 优化

常用优化点:

  • noParse
  • exclude
  • webpack.ignorePlugin
  • dllPlugin 动态链接库
module: {
        noParse: /jquery/,    // 独立依赖不再进行依赖分析
        rules: [
            {
                test: /\.js|jsx$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env'],
                        presets: ['@babel/preset-react'],
                    }
                }
            },
            {
                test: /\.css$/, use: [
                    { loader: 'style-loader', options: { insertAt: 'top' } },        // 对象方式  insertAt插入位置
                    { loader: 'css-loader', options: {} },
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html',
            filename: 'index.html',
        }),
        new webpack.IgnorePlugin(/\.\/locale/, /moment/),   //  不打包语言依赖包
        new webpack.DllReferencePlugin({
            manifest: path.resolve(__dirname, 'dist', 'manifest.json'),
        })
    ],

happypack 多线程打包

适用于大的项目,文件较小时多线程打包反而会慢

let Happypack = require('happypack');

module: {
        rules: [
            {
                test: /\.js|jsx$/,
                exclude: /node_modules/,
                use: 'Happypack/loader?id=js'
            },
        ]
    },
plugins: [
        ...
        new Happypack({
            id: 'js',
            use: [{ // 必须是数组
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    presets: ['@babel/preset-react'],
                }
            }]
        })
    ],

webpack自带优化

  • tree-shaking 仅支持import语法在生产模式下会自动去除掉没有用的代码
  • scop hosting 作用域提升简化代码

多页面打包抽取公共代码

entry: {
        index: './src/index.js',
        other: './src/other.js',
    },
optimization: {
    splitChunks: {
        cacheGroups: {
            common: {
                chunks: 'initial',
                minSize: 0,
                minChunks: 2,
            },
            vendor: {
                priority: 1,    // 权重优先
                test: /node_modules/,
                chunks: 'initial',
                minSize: 0,
                minChunks: 2,
            },
        }
    }
},