vue.config.js 打包优化
优化点
1.cdn配置
// 在module.exports外 添加如下代码
// 是否为生产环境
const isProduction = process.env.NODE_ENV !== "development";
// 本地环境是否需要使用cdn
const devNeedCdn = false;
const cdn = {
// cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
externals: {
vue: "Vue",
vuex: "Vuex",
"vue-router": "VueRouter",
axios: "axios",
"element-ui": "ELEMENT", //这里需要注意下得是全大写
},
// cdn的css链接
css: [
"https://unpkg.com/element-ui/lib/theme-chalk/index.css", //引入element ui css文件
],
// cdn的js链接
js: [
"https://cdn.bootcss.com/vue/2.6.10/vue.min.js", // vue必须在第一个
"https://cdn.bootcss.com/vuex/3.1.0/vuex.min.js",
"https://cdn.bootcss.com/vue-router/3.0.2/vue-router.min.js",
"https://cdn.bootcss.com/axios/0.18.1/axios.min.js",
"https://cdn.bootcdn.net/ajax/libs/echarts/5.3.0/echarts.common.min.js",
],
};
可参考BootCDN官方地址
在chainWebpack中输入如下代码
chainWebpack(config) {
// ============注入cdn start============
config.plugin("html").tap((args) => {
// 生产环境或本地需要cdn时,才注入cdn
if (isProduction || devNeedCdn) args[0].cdn = cdn;
return args;
});
// ============注入cdn end============
},
2.公共代码抽离
chainWebpack: config => {
/** 删除懒加载模块的 prefetch preload,降低带宽压力(使用在移动端) */
config.plugins.delete("prefetch").delete("preload");
// 代码分割
config.optimization.splitChunks({
chunks: "all",
cacheGroups: {
libs: {
name: "chunk-libs",
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: "initial",
},
elementUI: {
name: "chunk-elementUI",
priority: 20,
test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
},
commons: {
name: "chunk-commons",
test: resolve("src/components"),
minChunks: 3,
priority: 5,
reuseExistingChunk: true,
},
},
});
config.optimization.runtimeChunk("single");
}
3.代码压缩 去除线上环境的console.log代码
在module.exports外添加代码const UglifyJsPlugin = require(“uglifyjs-webpack-plugin”);
先下载插件 推荐使用cnpm ,用npm下载有一定概率网不好下载安装失败。
cnpm install uglifyjs-webpack-plugin --save-dev
在configureWebpack中添加如下代码
if (process.env.NODE_ENV === "production") {
return {
plugins: [
// 代码压缩
new UglifyJsPlugin({
//生产环境自动删除console
uglifyOptions: {
compress: {
drop_console: true, //注释console
drop_debugger: true, //注释debugger
pure_funcs: ["console.log"], //移除console.log
},
warnings: false,
cache: true,
parallel: true,
},
}),
],
};
}
4.图片压缩
cnpm install image-webpack-loader --save-dev
// ============压缩图片 start============
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
//{ bypassOnDebug: true }
mozjpeg: { progressive: true, quality: 65 }, // Compress JPEG images
optipng: { enabled: false }, // Compress PNG images
pngquant: { quality: [0.65, 0.9], speed: 4 }, // Compress PNG images
gifsicle: { interlaced: false }, // Compress SVG images
// webp: { quality: 75 }
})
.end();
// ============压缩图片 end============