webpack常规配置记录

430 阅读1分钟

vue.config.js

const name = 'vue3'
const CompressionPlugin = require("compression-webpack-plugin");
const zlib = require("zlib");
function resolve(dir) {
    return path.join(__dirname, dir)
}

module.exports = {
    publicPath: '/',
    outputDir: 'dist',
    assetsDir: 'static',
    lintOnSave: false,
    productionSourceMap: false,
    devServer: {
        port: 8081,
        open: true,
        proxy: {
            '/api': {
                target: 'http://xx.com',//不能为空
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            },
        }
    },
    configureWebpack: {
        name: name,
        resolve: {
            alias: {
                '@': resolve('src')
            }
        }
    },

    chainWebpack(config) {
        // it can improve the speed of the first screen, it is recommended to turn on preload
        // it can improve the speed of the first screen, it is recommended to turn on preload
        config.plugin('preload').tap(() => [
            {
                rel: 'preload',
                // to ignore runtime.js
                // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
                fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
                include: 'initial'
            }
        ])

        // when there are many pages, it will cause too many meaningless requests
        config.plugins.delete('prefetch')

        // set svg-sprite-loader
        config.module
            .rule('svg')
            .exclude.add(resolve('src/icons'))
            .end()
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
            .end()

        config
            .when(process.env.NODE_ENV !== 'development',
                config => {

                    config.plugin('CompressionPlugin').use(
                        // new CompressionPlugin({
                        //     filename: "[path][base].gz",
                        //     algorithm: "gzip",
                        //     test: /\.js$|\.css$|\.html$/,
                        //     threshold: 10240,
                        //     minRatio: 0.8,
                        // }),
                        new CompressionPlugin({
                            filename: "[path][base].br",
                            algorithm: "brotliCompress",
                            test: /\.(js|css|html|svg)$/,
                            compressionOptions: {
                                params: {
                                    [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
                                },
                            },
                            threshold: 10240,
                            minRatio: 0.8,
                            deleteOriginalAssets: false,
                        }),
                    );

                    config
                        .plugin('ScriptExtHtmlWebpackPlugin')
                        .after('html')
                        .use('script-ext-html-webpack-plugin', [{
                            // `runtime` must same as runtimeChunk name. default is `runtime`
                            inline: /runtime\..*\.js$/
                        }])
                        .end()

                    config
                        .optimization.splitChunks({
                            chunks: 'all',
                            cacheGroups: {
                                libs: {
                                    name: 'chunk-libs',
                                    test: /[\\/]node_modules[\\/]/,
                                    priority: 10,
                                    chunks: 'initial' // only package third parties that are initially dependent
                                },
                                elementUI: {
                                    name: 'chunk-elementUI', // split elementUI into a single package
                                    priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                                    test: /[\\/]node_modules[\\/]_?element-plus(.*)/ // in order to adapt to cnpm
                                },
                                commons: {
                                    name: 'chunk-commons',
                                    test: resolve('src/components'), // can customize your rules
                                    minChunks: 3, //  minimum common number
                                    priority: 5,
                                    reuseExistingChunk: true
                                }
                            }
                        })

                    config.optimization.minimizer('terser').tap(args => {
                        // 注释console.*
                        args[0].terserOptions.compress.drop_console = true;
                        // remove debugger
                        args[0].terserOptions.compress.drop_debugger = true;
                        // 移除 console.log
                        args[0].terserOptions.compress.pure_funcs = ['console.log'];
                        // 去掉注释 如果需要看chunk-vendors公共部分插件,可以注释掉就可以看到注释了
                        args[0].terserOptions.output = {
                            comments: false,
                        };
                        return args;
                    });

                    config.optimization.runtimeChunk('single')
                }
            )
    },
}

package.json

    "core-js": "^3.6.5",
    "element-plus": "^2.2.14",
    "vue": "^3.0.0",
    "zlib": "^1.0.5"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.15",
    "@vue/cli-plugin-eslint": "~4.5.15",
    "@vue/cli-service": "~4.5.15",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "compression-webpack-plugin": "^5.0.2",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0",
    "script-ext-html-webpack-plugin": "^2.1.5"
  },