当打包构建项目时,JavaScript包会变得非常大,影响页面加载,可以根据不同的路由对应的组件分割成不同的代码块,然后当路由访问这些文件时,再加载对应的组件。

    1. 参考文档:

    https://router.vuejs.org/zh/guide/advanced/lazy-loading.html

    1. 安装插件

    npm install —save-dev @babel/plugin-syntax-dynamic-import

    1. 修改babel.config.js配置文件

      1. // 项目发布节点用到的babel插件
      2. const prodPlugins = []
      3. // 如果处于发布模式,开启transform-remove-console
      4. if(process.env.NODE_ENV === 'production'){
      5. prodPlugins.push('transform-remove-console')
      6. }
      7. module.exports = {
      8. presets: [
      9. ['@vue/cli-plugin-babel/preset', {'modules': false}]
      10. ],
      11. plugins: [
      12. [
      13. "component",
      14. {
      15. "libraryName": "element-ui",
      16. "styleLibraryName": "theme-chalk"
      17. }
      18. ],
      19. // 产品发布时使用的配置(移除所有的console.log)
      20. ...prodPlugins,
      21. // 开启路由懒加载
      22. '@babel/plugin-syntax-dynamic-import'
      23. ]
      24. }
    2. 修改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) ```

    1. 打包文件效果

    image.png