0

vue代码压缩优化

 1 year ago
source link: https://www.fly63.com/article/detial/12303
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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
        })
    )
}

对于css代码你可以使用 cssnano-webpack-plugin 插件来压缩 CSS 代码:

const CssnanoWebpackPlugin = require('cssnano-webpack-plugin');

module.exports = {
plugins: [
new CssnanoWebpackPlugin({})
]
}

3、图片资源压缩

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

npm install image-webpack-loader --save
chainWebpack: config => {
     config.module
           .rule('images')
           .use('image-webpack-loader')
           .loader('image-webpack-loader')
           .options({ bypassOnDebug: true })
           .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不删除源文件
 }))

链接: https://www.fly63.com/article/detial/12303


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK