继续操作前请注册或者登录。

Vue Cli3项目的打包优化


Vue Cli3项目的打包优化
使用vue cli3创建一个项目,在项目根目录下创建配置文件vue.config.js
vue.config.js 是一个可选的审查或修改全局的 CLI 配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载
vue.config.js:
module.exports = {   // 选项...}
打包优化:
关闭source map
在项目打包时,会生成一些经过压缩加密的source map文件(.map文件),这些source map文件用于准确输出报错代码的位置。可以设置 productionSourceMap 为 false,不再生成source map文件,减少打包后文件的大小
vue.config.js:
module.exports = {    productionSourceMap: false}
cdn引入外部库
在项目打包时,项目中的所有js,css文件都会被打包,可能会导致打包文件过大,可以通过cdn引入需要的外部库文件,减少打包后文件的大小
index.html
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width,initial-scale=1.0">    <link rel="icon" href="<%= BASE_URL %>favicon.ico">    <title>title</title>     <!---cdn引入外部库文件--->    <script src="https://cdn.bootcss.com/vue/2.5.2/vue.min.js"></script>    <script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>    <script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>  </head>  <body>    <div id="app"></div>  </body></html>
vue.config.js:
module.exports = {   configureWebpack: {      //配置externals,防止cdn引入的外部库打包      externals: {         "vue": "Vue",         "vue-router": "VueRouter",         "vuex": "Vuex"      }   }}
组件按需引入
在项目中使用外部组件库时,例如 element-ui 组件库可能太大,会导致打包文件过大,可以通过 babel-plugin-component 插件按使用需要只引入使用的组件,减小打包文件大小
安装 babel-plugin-component
npm i babel-plugin-component -D
babel.config.js:
module.exports = {  presets: [    '@vue/app'  ],  plugins: [    [      'component',      {        'libraryName': 'element-ui',        'styleLibraryName': 'theme-chalk'      }    ]  ]}
main.js:
// 注释掉 element-ui 组件的全部引入// import ElementUI from 'element-ui'// Vue.use(ElementUI)// 按需引入需要的组件import { Input, Button, Icon } from 'element-ui'Vue.use(Input)Vue.use(Button)Vue.use(Icon)
路由懒加载
为了更好的客户体验,首屏组件加载速度更快,解决白屏问题,可以通过路由懒加载,在需要的时候进行按需加载
通过 resolve
router.js:
import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)var router =  new Router({  routes: [    {      path: '/',      name: 'home',      component: resolve => require(['@/views/home'],resolve)    },    {      path: '/list',      name: 'list',      component: resolve => require(['@/views/list'],resolve)    }  ]})
通过 import
router.js:
import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)var router =  new Router({  routes: [    {      path: '/',      name: 'home',      component: () => import("@/views/home")    },    {      path: '/list',      name: 'list',      component: () => import('@/views/list')    }  ]})
图片压缩
在项目打包时,图片文件太大会导致打包后文件过大,可以通过 image-webpack-loader 插件将图片进行压缩来减少打包后文件的大小
安装 image-webpack-loader
npm install image-webpack-loader --save-dev
vue.config.js:
// 是否为生产环境const isProduction = process.env.NODE_ENV !== 'development'module.exports = { // 生产环境相关配置    if (isProduction) {        //压缩图片        chainWebpack: config => {            config.module               .rule('images')               .use('image-webpack-loader')               .loader('image-webpack-loader')               .options({                    bypassOnDebug: true     })               .end()        }    }}
gzip 压缩
gizp压缩是一种http请求优化方式,可以使用 compression-webpack-plugin 插件,通过对html、js、css文件甚至json数据压缩,可以减小60%以上的文件体积,来提高加载速度
安装compression-webpack-plugin
npm install compression-webpack-plugin --save-dev
vue.config.js:
// 是否为生产环境const isProduction = process.env.NODE_ENV !== 'development'// gzip压缩const CompressionWebpackPlugin = require('compression-webpack-plugin')module.exports = {     // 生产环境相关配置     if (isProduction) {          // gzip压缩          const productionGzipExtensions = ['html', 'js', 'css']          config.plugins.push(             new CompressionWebpackPlugin({                filename: '[path].gz[query]',                algorithm: 'gzip',                test: new RegExp(                    '\\.(' + productionGzipExtensions.join('|') + ')$'                ),                threshold: 10240,  //只有大小大于10240的资源会被处理                 minRatio: 0.8,  //只有压缩率小于0.8的资源才会被处理                deleteOriginalAssets: true  //删除原文件             })         ) }}
到顶部