Vue Cli3配置文件优化处理

1、设置productionSourceMap为false

如果不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。

设置为false打包时候不会出现.map文件

module.exports = {
    productionSourceMap: false
}

2、代码压缩

安装uglifyjs-webpack-plugin插件,可以去除项目中console.log和debugger

npm install uglifyjs-webpack-plugin --save
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
// 生产环境相关配置
if (isProduction) {
    // 代码压缩
    config.plugins.push(
        new UglifyJsPlugin({
            uglifyOptions: {
                //生产环境去除console等信息
                compress: {
                    warnings: false, // 若打包错误,则注释这行
                    drop_debugger: true,//是否移除debugger
                    drop_console: true,
                    pure_funcs: ['console.log']//移除console
                }
            },
            sourceMap: false,
            parallel: true
        })
    )
}

3、图片资源压缩

安装 image-webpack-loader 插件,可以将大图片进行压缩从而缩小打包体积

npm install image-webpack-loader --save
    chainWebpack: config => {
        // ============压缩图片 start============
        config.module
            .rule('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true })
            .end()
        // ============压缩图片 end============
    }

4、开启gzip压缩

开启gzip压缩,可以优化http请求,提高加载速度

npm install compression-webpack-plugin --save-dev
const CompressionPlugin = require("compression-webpack-plugin");
// 开启gzip压缩
config.plugins.push(new CompressionPlugin({
    algorithm: 'gzip',
    test: new RegExp("\\.(" + ["js", "css"].join("|") + ")$"), // 匹配文件扩展名
    // threshold: 10240, // 对超过10k的数据进行压缩
    threshold: 5120, // 对超过5k的数据进行压缩
    minRatio: 0.8,
    cache: true, // 是否需要缓存
    deleteOriginalAssets:false  // true删除源文件(不建议);false不删除源文件
 }))