当打包构建项目时,JavaScript包会变得非常大,影响页面加载,可以根据不同的路由对应的组件分割成不同的代码块,然后当路由访问这些文件时,再加载对应的组件。
- 参考文档:
https://router.vuejs.org/zh/guide/advanced/lazy-loading.html
- 安装插件
npm install —save-dev @babel/plugin-syntax-dynamic-import
修改babel.config.js配置文件
// 项目发布节点用到的babel插件
const prodPlugins = []
// 如果处于发布模式,开启transform-remove-console
if(process.env.NODE_ENV === 'production'){
prodPlugins.push('transform-remove-console')
}
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', {'modules': false}]
],
plugins: [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
],
// 产品发布时使用的配置(移除所有的console.log)
...prodPlugins,
// 开启路由懒加载
'@babel/plugin-syntax-dynamic-import'
]
}
修改src/router/index.js路由规则配置文件 ```javascript import Vue from ‘vue’ import VueRouter from ‘vue-router’ // import Login from “@/components/Login” // import Home from “@/components/Home”; // import Welcome from “@/components/Welcome”; // import Users from “@/components/user/Users”; // import Rights from “@/components/power/Rights”; // import Roles from “@/components/power/Roles”; // import Cate from “@/components/goods/Cate”; // import Params from “@/components/goods/Params”; // import GoodList from “@/components/goods/List” // import GoodAdd from “@/components/goods/Add” // import Order from “@/components/order/Order”; // import Report from “@/components/report/Report”; // import Home from ‘../views/Home.vue’
const Login = () => import(/ webpackChunkName: “login_home_welcome” / ‘@/components/Login’) const Home = () => import(/ webpackChunkName: “login_home_welcome” / ‘@/components/Home’) const Welcome = () => import(/ webpackChunkName: “login_home_welcome” / ‘@/components/Welcome’)
const Users = () => import(/ webpackChunkName: “users” / ‘@/components/user/Users’)
const Rights = () => import(/ webpackChunkName: “power” / ‘@/components/power/Rights’) const Roles = () => import(/ webpackChunkName: “power” / ‘@/components/power/Roles’)
const Cate = () => import(/ webpackChunkName: “goods” / ‘@/components/goods/Cate’) const Params = () => import(/ webpackChunkName: “goods” / ‘@/components/goods/Params’) const GoodList = () => import(/ webpackChunkName: “goods” / ‘@/components/goods/List’) const GoodAdd = () => import(/ webpackChunkName: “goods” / ‘@/components/goods/Add’)
const Order = () => import(/ webpackChunkName: “order” / ‘@/components/order/Order’)
const Report = () => import(/ webpackChunkName: “report” / ‘@/components/report/Report’)
Vue.use(VueRouter) ```
- 打包文件效果