1. 起因
项目打包的时候发现部分文件过大: vender.JS 有 400K,App.CSS 高达 1.6M. 看着这个数值, 瞬间凌乱.
2. 优化
2.1 优化 vender.JS
是因项目的依赖 vue,vue-router,vuex,axios 造成的, 可使用 cdn, 注意更换对应版本号
- <script src="//cdn.bootcss.com/vue/2.5.2/vue.min.js">
- </script>
- <script src="//cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js">
- </script>
- <script src="//cdn.bootcss.com/vuex/3.0.1/vuex.min.js">
- </script>
在 build/webpack.base.conf.JS 中添加如下代码, 使其不打包进文件
- module.exports = {
- //...
- externals: {
- 'vue': 'Vue',
- 'vue-router': 'VueRouter',
- 'vuex':'Vuex'
- },
- //...
- }
去掉相关引用代码
- // import Vue from 'vue'
- // import Router from 'vue-router'
- // import Vuex from 'vuex'
2.2 优化 App.CSS
是因项目 CSS 中使用的图片全部转成了 base64 写入了 CSS 中, 导致 App.CSS 体积过大, 首屏加载过慢, 在 build/webpack.base.conf.JS 中设置图片下的 url-loader 的大小限制
- module: {
- rules: [
- //...
- {
- {
- test: /\.(PNG|jpe?g|gif|svg)(\?.*)?$/,
- loader: 'url-loader',
- options: {
- name: utils.assetsPath('img/[name].[ext]'),
- limit:50 //<-- 添加此行, 单位为 b, 表示将图片大小 <=50b 的图片转成 base64 格式
- }
- },
- }
- //...
- ]}
- // --------------------- 打包后可能会出现 CSS 中的图片路径不对的情况, 修改如下代码:
- // build/utils.JS 中找到 vue-style-loader
- if (options.extract) {
- return ExtractTextPlugin.extract({
- use: loaders,
- fallback: 'vue-style-loader',
- publicPath:'../../' // <-- 添加此行代码
- })
- } else {
- return ['vue-style-loader'].concat(loaders)
- }
2.3 启用 Gzip 压缩, 一般浏览器都已支持. gz 的资源文件, 在 http 请求的 Request Headers 中能看到 Accept-Encoding:gzip
- //config/index.JS 中招到 productionGzip 设置为 true
- build: {
- //...
- productionGzip:true,
- productionGzipExtensions: ['js', 'css'],
- }
- //build/webpack.prod.conf.JS 中添加以下代码
- if (config.build.productionGzip) {
- const CompressionWebpackPlugin = require('compression-webpack-plugin')
- webpackConfig.plugins.push(
- new CompressionWebpackPlugin({
- asset: '[path].gz[query]',
- algorithm: 'gzip',
- test: new RegExp(
- '\\.(' +
- config.build.productionGzipExtensions.join('|') +
- ')$'
- ),
- threshold: 10240,
- // deleteOriginalAssets:true, // 删除源文件, 不建议
- minRatio: 0.8
- })
- )
- }
来源: https://www.cnblogs.com/shenmissing/p/9933450.html