[英]How to properly lazy load vuejs components in router
我在路由器中延迟加载组件时遇到问题
这是我的router / index.js文件
import Vue from "vue";
import Router from "vue-router";
import routes from './routes'
Vue.use(Router);
export default new Router({
routes,
mode: 'history',
base: __dirname,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
return { x: 0, y: 0 }
}
});
这是我的routes.js文件,用于存储路由
import {Trans} from '@/plugins/Translation'
function load(component) {
return () => import(/* webpackChunkName: "[request]" */ `@/components/${component}.vue`)
}
// I have also tried this way
//Vue.component(
// 'async-webpack-example',
// // The `import` function returns a Promise.
// () => import('./my-async-component')
//)
export default [
{
path: '/:lang',
component: {
template: '<router-view></router-view>'
},
beforeEnter: Trans.routeMiddleware,
children: [
{
path: "/",
name: "Home",
component: load('Home')
},
{
path: "/contact",
name: "Contact",
component: load('Contact')
},
...
// Many more other routes
...
{
path: '*',
redirect: load('404')
}
]
}
]
问题是我一直在收到错误
ERROR in ./src/router/routes.js
Module build failed: SyntaxError: Unexpected token (4:17)
2 |
3 | function load(component) {
> 4 | return () => import(/* webpackChunkName: "[request]" */ `@/components/${component}.vue`)
| ^
5 | }
6 |
7 |
我也试过加载这种方式,但我一直得到同样的错误
const Test = () => import('@/components/Test');
然后路线看起来像
{
path: "/",
name: "Home",
component: Test
}
但问题看起来一样。
有人可以帮我弄清楚,我错过了什么。 如果您需要任何其他信息,请告诉我,我会提供。 谢谢
我正在使用此语法进行延迟加载。 检查此语法,这将解决您的问题。
const Test = resolve => require(['@/components/Test/index'], resolve);
最后,我找到了使用上层语法的解决方案,这导致了我的问题。 因此,如果您想以这种方式导入组件
return () => import(/* webpackChunkName: "[request]" */ `@/components/${component}.vue`)
然后你需要使用babel
首先你需要安装
npm install --save-dev babel-plugin-syntax-dynamic-import
然后创建一个文件.babelrc(在你的根文件夹中),该文件的内容应该是
{
"plugins": ["syntax-dynamic-import"]
}
然后开始你的npm你怎么开始它。 npm run dev
这将使您能够使用上层语法延迟加载组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.