前言:
在日常开发中我们离不开打包工具webpack,但是不同的配置会影响我们项目的运行构建时间,也会影响打包之后项目包的大小,这篇文章记录一下我使用过的可以优化webpack的配置。
注:以本专栏上篇文章里面的vue.config.js为基础,去加配置
一、压缩图片
1、先下载依赖
npm install --save-dev image-webpack-loader
2、在vue.config.js的module.exports上面先定义设置值
①默认设置:(4m的图片使用默认设置压缩成1.4m)
const defaultoptions = { bypassondebug: true, };
②自定义设置
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中加入配置:
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加入配置:
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、先下载依赖
npm install uglifyjs-webpack-plugin --save-dev
2、在vue.config.js的第一行引入依赖
const uglifyplugin = require("uglifyjs-webpack-plugin");
3、在configurewebpack中加入配置:
config.plugins.push( new uglifyplugin({ uglifyoptions: { //生产环境自动删除console compress: { drop_debugger: true, drop_console: true, pure_funcs: ["console.log"], }, }, sourcemap: false, parallel: true, }) );
以上就是在vue.config.js中优化webpack配置的方法的详细内容,更多关于vue.config.js优化webpack的资料请关注代码网其它相关文章!
发表评论