Vue.js关于打包时(build)进行体积优化的一些总结

解决vue打包时,包体积过大导致上线后访问体验不佳的问题

第一次打包如果失败记得打包第二次

1、利用cdn节点进行引入的优化

运行代码时,代码会运行一条再执行下一条,所以我们运用cdn,来缓解压力,让页面的反应更加快捷

将main.js中用 import 数据删掉

在public/index.html 中加入如下引用

    
    
    
    
    
    
    
    
    
    
    
    

在 vue.config.js 中加入:

config. set(' externals',{
	vue: 'Vue'
	axios:' axios' ,
	lodash:'_'
	moment: ' moment ' ,
   'vue-quill-editor' : ' vueQuillEditor'
})

然后打包就行了

2、路由懒加载

懒加载又叫做延迟加载,就是随用随加载,利用懒加载对页面进行划分,可以分担压力,减少加载用时,有利于用户体验
重新打包以后,大文件会被分割成一个个小文件
babel 安装命令:
npm install --save-dev @babel/plugin-syntax-dynamic-import
进行配置
module . exports = {
	presets:[
		' @vue/cli-plugin- babel/ preset'
	plugins: [
		... prodplugins,
		"@babel/plugin-syntax- dynamic - import"
	]
}
修改文件index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import(/* webpackChunkName: "group-login" */ '../components/Login.vue')
 
const Home = () => import(/* webpackChunkName: "group-common" */ '../components/Home.vue')
const Welcome = () => import(/* webpackChunkName: "group-common" */ '../components/Welcome.vue')
 
const Users = () => import(/* webpackChunkName: "group-rights" */ '../components/user/Users.vue')
const Rights = () => import(/* webpackChunkName: "group-rights" */ '../components/power/Rights.vue')
const Roles = () => import(/* webpackChunkName: "group-rights" */ '../components/power/Roles.vue')
 
const Category = () => import(/* webpackChunkName: "group-category" */ '../components/goods/Category.vue')
const Params = () => import(/* webpackChunkName: "group-category" */ '../components/goods/Params.vue')
 
const GoodsList = () => import(/* webpackChunkName: "group-goods" */ '../components/goods/GoodsList.vue')
const GoodsAdd = () => import(/* webpackChunkName: "group-goods" */ '../components/goods/GoodsAdd.vue')
 
const Order = () => import('../components/order/Order.vue')
const Report = () => import('../components/reports/Report.vue')

3、移除console

在我们进行调试的时候,需要用到console输出数据来进行自我检测,但是上线后用不到console,所以我们应该进行删除,否则会有警告错误

利用 terser-webpack-plugin 插件

安装命令:

npm install terser-webpack-plugin --save-dev
然后在 babel.config 文件下进行如下配置
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin()],
    terserOptions: {
      compress: {
        drop_console: true
      }
    }
  }
}

你可能感兴趣的:(Vue.js关于打包时(build)进行体积优化的一些总结)