前端文件的压缩主要是资源图片以及js和css压缩,今天分享一下vue项目中的文件压缩方法。


压缩js和css

如果你使用的是 webpack v5 或更高版本,是开箱机带的功能,但是你的webpack是5以下或则希望自定义配置,那么需要安装 ​​terser-webpack-plugin​​​。如果使用 webpack v4,则必须安装 ​​terser-webpack-plugin​​ v4 的版本。

// vue.config.js
const TerserJSPlugin = require('terser-webpack-plugin');
....
chainWebpack: (config) => {
// 开启js、css压缩
config.plugin('TerserJSPlugin')
.use(new TerserJSPlugin({
terserOptions: {
output: {
comments: false // 去掉注释
},
warnings: false,
compress: {
// eslint-disable-next-line camelcase
drop_console: true,
// eslint-disable-next-line camelcase
drop_debugger: true,
// pure_funcs: ['console.log'] // 移除console
}
}
}));
}
图片压缩

安装图片压缩的loader​​image-webpack-loader​​​ 直接终端​​npm install image-webpack-loader -D​

// vue.config.js
...
module.exports = {
...
chainWebpack: config => {
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
bypassOnDebug: true, // webpack 'debug'


作者:挣扎在温饱线上的前端农民工
链接:https://juejin.cn/post/7080066104613142559
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。