production环境打包优化
- 性能优化 UglifyJsPlugin ,压缩混淆去除注释和console // npm install uglifyjs-webpack-plugin -D
- cdn的使用,externals排除打包外
- gzip压缩 npm i compression-webpack-plugin@6.1.1 -D`
vue.config.js文件配置
// npm run build 自动设置process.env.NODE_ENV => 'production'
// npm run serve 则会设置为devlopment
const isProduction = process.env.NODE_ENV === 'production';
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const plugins = [];
let externals = {};
const cdn = {
dev:{
css:[],js:[]
},
build:{
css:[],
js:[
'https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js',
'https://cdn.bootcss.com/vue/2.6.11/vue.min.js',
'https://cdn.bootcss.com/vue-router/3.5.4/vue-router.min.js',
]
}
}
if (isProduction) {
// 压缩 混淆 取出注释 去除console
plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: false, // 去除注释
},
warnings: false, // 去除黄色警告,
compress: {
drop_console: true,
drop_debugger: false, // 特定情况需要利用debugger防止调试
pure_funcs: ['console.log'], // 移除console.log 避免console.error
}
}
})
);
plugins.push(new CompressionWebpackPlugin({
test:/\.(js|json|css)$/i, // 图片一般不Gzip压缩 webpack-image-loader
threshold:10240, // 只有在10kb以上才压缩
})
)
// 附加全局引包的引用关系
externals = {
// from后的 : 使用全局暴露的对象名,具体看包暴露哪个
vue:'Vue',
'vue-router':'VueRouter',
axios:'axios'
}
}
module.exports = {
productionSourceMap: !isProduction,
configureWebpack: {
devServer: {
proxy: {
'/api': {
target: 'http://1.116.64.64:5004/',
changeOrigin: true
}
}
},
plugins,
externals
},
chainWebpack:config=>{
// html-webpack-plugin
config.plugin('html').tap(args=>{
if (isProduction) {
// htmlWebpackPlugin.options.cdn
args[0].cdn = cdn.build
}else {
args[0].cdn = cdn.dev;
}
return args;
});
}
}
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
<% for (var i in
htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %>
<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>"/>
<% } %>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<% for (var i in
htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
<script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
<% } %>
</body>
</html>