[Vue] Code split by route in VueJS

In this lesson I show how to use webpack to code split based on route in VueJS. Code splitting is a useful tool to help eliminate unused code and only load what's necessary.

Additional Resources https://router.vuejs.org/en/advanced/lazy-loading.html

 

After generate the project by Vue-cli, make sure those dependencies were installed already:

npm i babel-eslint babel-plugin-syntax-dynamic-import eslint-plugin-import -D

 

.eslintrc.js:

module.exports = {
  root: true,
  parserOptions: { parser: "babel-eslint" },
  extends: ["plugin:vue/essential", "@vue/prettier"]
};

 

.babelrc:

{
  "presets": ["@vue/app"],
  "plugins": ["syntax-dynamic-import"]
}

 

routes.js:

复制代码
import Vue from "vue";
import Router from "vue-router";
const Home = () => import(/* webpackChunkName: "Home" */ "./views/Home.vue");
const About = () => import(/* webpackChunkName: "About" */ "./views/About.vue");

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/about",
      name: "about",
      component: About
    }
  ]
});
复制代码

 

The same for lazy loading a component:

复制代码
<template>
  ...
    <h3>Modal Example</h3>
    <button @click="show">Show Modal</button>
  </div>
</template>

<script>
const MyModal = () => import("@/components/MyModal.vue"); // lazy loading the component
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  methods: {
    show () {
      this.$modal.show(MyModal);
    },
  }
};
</script>
复制代码

 

posted @   Zhentiw  阅读(480)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-05-26 [RxJS] Convert RxJS Subjects to Observables
2017-05-26 [HTTP] Understand 2xx HTTP Status Code Responses
2017-05-26 [React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component
2016-05-26 [PWA] Enable Push Notification in your web app
2016-05-26 [RxJS] Combination operator: withLatestFrom
2016-05-26 [RxJS] Combination operator: zip
2016-05-26 [RxJS] Combination operator: combineLatest
点击右上角即可分享
微信分享提示