前端- [Vue] vue 2.x项目生产编译优化缩短编译时间

代码解释
关闭 source map:productionSourceMap: false 可以避免生成生产环境的 source map 文件,从而减少编译时间和包的大小。
使用 CompressionPlugin:在构建时开启 gzip 压缩,减小文件体积,加快传输速度。
使用 HardSourceWebpackPlugin:为模块提供中间缓存,第一次构建时会花费较长时间,但后续构建会显著加快。
使用 TerserPlugin:对代码进行压缩,移除 console 和 debugger 语句,减少代码体积。
代码分割:通过 splitChunks 配置将代码分割成更小的块,提高加载性能和缓存效率。
移除 prefetch 和 preload 插件:避免不必要的资源预加载,减少编译时间。
并行构建:设置 parallel 为 true,利用多核 CPU 进行并行构建,加快编译速度。
通过以上优化措施,可以显著缩短 Vue 2.x 项目的生产编译时间。
const CompressionPlugin = require('compression-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
vue.config.js
module.exports = {

// 基础路径,可根据项目部署情况修改
publicPath: './',
productionSourceMap: false,
configureWebpack: {
    plugins: [
        // 开启 gzip 压缩
        new CompressionPlugin({
            algorithm: 'gzip',
            test: /\.(js|css)$/,
            threshold: 10240,
            minRatio: 0.8
        }),
        // 缓存编译结果
        new HardSourceWebpackPlugin()
    ],
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    compress: {
                        // 移除 console 语句
                        drop_console: true,
                        drop_debugger: true
                    }
                }
            })
        ],
        // 分割代码
        splitChunks: {
            chunks: 'all'
        }
    }
},
chainWebpack: config => {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch');
    // 移除 preload 插件
    config.plugins.delete('preload');
},
parallel: require('os').cpus().length > 1

};

你可能感兴趣的:(前端)