vue打包优化
1、对项目打包文件进行gzip压缩,插件“compression-webpack-plugin”,在vue.config.js中配置
yarn add compression-webpack-plugin -D // 如果报错,就降版本5.0.1
const path = require("path");
const CompressionPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = { chainWebpack: config => { config.resolve.alias["@"] = resolve("src"); if (process.env.NODE_ENV === "production") { config.plugin("compressionPlugin").use( new CompressionPlugin({ filename: "[path].gz[query]", algorithm: "gzip", test: productionGzipExtensions, threshold: 10240, // 处理大于这个字节的文件 minRatio: 0.8, deleteOriginalAssets: false }) ); } }, };
2、可视化插件webpack-bundle-analyzer
yarn add webpack-bundle-analyzer -D // 在vue.config.js中配置
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
configureWebpack: config => {if (process.env.NODE_ENV === "production") { config.plugins.push( new BundleAnalyzerPlugin() ); } }
3、去除项目中的console.log()
yarn add terser-webpack-plugin -D
configureWebpack: (config) => { if (process.env.NODE_ENV === "production") { config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true; } }
4、使用CDN
(1)index.html 中直接使用 <script src="//cdn.bootcss.com/echarts/4.2.1/echarts.simple.min.js"></script>
(2)在vue.config.js中配置
module.exports = { configureWebpack: { externals: { 'echarts': 'echarts' // 配置使用CDN } } }
(3)在文件中直接import使用就行