vue代码压缩优化
设置productionSourceMap为false
如果不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
设置为false打包时候不会出现.map文件
module.exports = {
? ? productionSourceMap: false
}
代码压缩
安装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
? ? ? ? })
? ? )
}
图片资源压缩
安装 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============
? ? }
开启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不删除源文件
?}))
vuecli3代码压缩混淆
最近被某大公司大佬虐了,要求混淆用vuecli3写的代码(啥敏感信息都没有,混淆个什么混淆...)
现将混淆流程记录如下
1、安装 “uglifyjs-webpack-plugin”
cnpm i --save uglifyjs-webpack-plugin
没有安装cnpm的同学可以用npm
2、在项目根目录下创建一个名为 vue.config.js的文件
3、在vue.config.js中引入uglifyjs-webpack-plugin
const UglifyPlugin = require('uglifyjs-webpack-plugin')
4、在vue.config.js中配置uglifyjs-webpack-plugin
module.exports = {
? configureWebpack: (config) => {
? ? if (process.env.NODE_ENV == 'production') {
? ? ? // 为生产环境修改配置
? ? ? config.mode = 'production'
? ? ? // 将每个依赖包打包成单独的js文件
? ? ? let optimization = {
? ? ? ? minimizer: [new UglifyPlugin({
? ? ? ? ? ? uglifyOptions: {
? ? ? ? ? ? ? ? warnings: false,
? ? ? ? ? ? ? ? compress: {
? ? ? ? ? ? ? ? ? drop_console: true,?
? ? ? ? ? ? ? ? ? drop_debugger: false,
? ? ? ? ? ? ? ? ? pure_funcs: ['console.log']?
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ?})]
? ? ? }
? ? ? Object.assign(config, {
? ? ? ? optimization
? ? ? })
? ? } else {
? ? ? // 为开发环境修改配置
? ? ? config.mode = 'development'
? ? }
? }
};
这就可以了,接下来大家可以打包试试了
cnpm run build
如果报错的话,估计是uglifyjs-webpack-plugin版本又更新了,可能需要修改配置中的 “minimizer”节点,官方文档地址:https://www.npmjs.com/package/uglifyjs-webpack-plugin
以上为个人经验,希望能给大家一个参考,也希望大家多多支持源码搜藏网。