webpack动态导入文件报错的解决方法

在进行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路由懒加载



转载于:https://juejin.im/post/5d5bd2d1f265da03ce39dae2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值