前言:
在日常开发中我们离不开打包工具webpack,但是不同的配置会影响我们项目的运行构建时间,也会影响打包之后项目包的大小,这篇文章记录一下我使用过的可以优化webpack的配置。
注:以本专栏上篇文章里面的vue.config.js为基础,去加配置
一、压缩图片
1、先下载依赖
npm install --save-dev image-webpack-loader
2、在vue.config.js的module.exports上面先定义设置值
①默认设置:(4M的图片使用默认设置压缩成1.4M)
javascript
const defaultOptions = {
bypassOnDebug: true,
};
②自定义设置
javascript
const customOptions = {
mozjpeg: {
progressive: true,
quality: 50
},
optipng: {
enabled: true,
},
pngquant: {
quality: [0.5, 0.65],
speed: 4
},
gifsicle: {
interlaced: false,
},
// 不支持WEBP就不要写这一项
webp: {
quality: 75
}
}
3、在chainWebpack中加入配置:
javascript
chainWebpack: config => {
config.module.rule('images')
.test(/\.(gif|png|jpe?g|svg)$/i)
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options(customOptions)
.end()
}
options中可以切换使用默认还是自定义
二、公共代码抽离:
在configureWebpack加入配置:
javascript
configureWebpack: (config) => {
config.optimization = {
splitChunks: {
cacheGroups: {
vendor: {
chunks: "all",
test: /node_modules/,
name: "vendor",
minChunks: 1,
maxInitialRequests: 5,
minSize: 0,
priority: 100,
},
common: {
chunks: "all",
test: /[\\/]src[\\/]js[\\/]/,
name: "common",
minChunks: 2,
maxInitialRequests: 5,
minSize: 0,
priority: 60,
},
styles: {
name: "styles",
test: /\.(sa|sc|c)ss$/,
chunks: "all",
enforce: true,
},
runtimeChunk: {
name: "manifest",
},
},
},
};
}
三、对代码进行压缩,并移除控制台输出
1、先下载依赖
javascript
npm install uglifyjs-webpack-plugin --save-dev
2、在vue.config.js的第一行引入依赖
javascript
const UglifyPlugin = require("uglifyjs-webpack-plugin");
3、在configureWebpack中加入配置:
javascript
config.plugins.push(
new UglifyPlugin({
uglifyOptions: {
//生产环境自动删除console
compress: {
drop_debugger: true,
drop_console: true,
pure_funcs: ["console.log"],
},
},
sourceMap: false,
parallel: true,
})
);