在进行webpack搭建单页面应用时,使用到了vue-router,配置路由的过程中,出现import语法错误。针对此现象,我们一起来分析下。
路由配置的代码如下:
const routes = [{
path: '/customer01',
name: 'customer',
component: () => import('../../views/customer/Index.vue')
}];
export default routes;复制代码
报错内容如下:
ERROR in ./src/router/customer/index.js
Module build failed (from ./node_modules/_babel-loader@7.1.5@babel-loader/lib/index.js):
SyntaxError: D:/web4/webpack_spa_demo/src/router/customer/index.js: Unexpected token (5:25)
3 | path: '/customer01',
4 | name: 'customer',
> 5 | component: () => import('./views/customer/Index.vue')
| ^
6 | }
7 | ];
8 | export default routes;复制代码
分析
import报错了,已经安装babel的插件。 在vue-router官网上有一段提示,如果使用的是 Babel,你将需要添加 syntax-dynamic-import 插件,才能使 Babel 可以正确地解析语法。
所以解决办法如下:
首先安装插件: babel-plugin-dynamic-import-webpack
方案一
在配置文件中,引入插件:
{ "presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}]
],
"plugins": ['dynamic-import-webpack']
}复制代码
方案二
在webpack.config文件中配置相应的插件:
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {//如果有这个设置则不用再添加.babelrc文件进行配置
"babelrc": false,// 不采用.babelrc的配置
"plugins": [
"dynamic-import-webpack"
]
}
}
]}复制代码
总结,官方文档需要多多看,详见地址vue-router路由懒加载。