vue-cli 3.0 路由懒加载
当打包构建应用时,Javascript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
1. 安装 syntax-dynamic-import 插件
如果在 vue-cli 使用了 babel ,需要添加 syntax-dynamic-import
插件,才能使 Babel 可以正确地解析语法。
$ npm install --save-dev @babel/plugin-syntax-dynamic-import
安装完成后,配置文件 babel.config.js
module.exports = {
"presets": [
"@vue/app"
],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
},
"syntax-dynamic-import"
]
]
}
2. 修改路由配置
在 router.js 中的组件引用,作如下改动:
// import Login from '@/views/users/Login'
// import Register from '@/views/users/Register'
// import Home from './views/Home.vue'
// import Report from '@/views/Report.vue'
const Login = () => import(/* webpackChunkName: "users" */ '@/views/users/Login.vue')
const Register = () => import(/* webpackChunkName: "users" */ '@/views/users/Register.vue')
const Home = () => import(/* webpackChunkName: "home" */ '@/views/Home.vue')
const Report = () => import(/* webpackChunkName: "report" */ '@/views/Report.vue')
其中 /* webpackChunkName: "home" */
是一个特殊的注释语法,用来提供 chunk name (需要 Webpack > 2.4)。上面处理后,打包的dist目录下的文件如下:
dist/js/chunk-vendors.70d314fb.js
dist/js/app.ff1d5c7f.js
dist/js/report.6c761e68.js
dist/js/home.fe0e7528.js
dist/js/users.ade47d0f.js
dist/css/chunk-vendors.a33b2b12.css
dist/css/app.133be4a7.css
dist/css/report.1d10a2c7.css
dist/css/users.c53bf6b0.css
dist/css/home.122162a2.css