VueJS。模块解析失败:意外的令牌 <

时间:2021-01-22 11:45:57

标签: vue.js jsx babel-loader

我的一个 .vue 脚本有这个导入语句:

import ElSlider from 'element-ui/packages/slider/src/main.vue'

问题是,当它编译时,它会抛出一个错误:

Failed to compile.

./node_modules/element-ui/packages/slider/src/marker.js 13:6
Module parse failed: Unexpected token (13:6)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
|     return (
>       <div class="el-slider__marks-text" style={ this.mark.style || {} }>
|         { label }
|       </div>

如您所见,源代码包含以下几行:

 return (
 <div class="el-slider__marks-text" style={ this.mark.style || {} }>
 { label }
 </div>

而且看起来,Vue 默认不喜欢这种语法。我尝试在 vue.config.js 中指定一个加载器,如下所示:

   ...
   chainWebpack: config => {

    config.module
    .rule('jsx')
    .test(/marker\.js$/)
    .use('babel-loader')
    .loader('babel-loader')
    .tap(options => {
      options.presets = ["jsx", "es2015"]
      return options
    })

但这无济于事。如果重要的话,我还修改了 babel.config.js。所以现在看起来像:

 module.exports = {
   presets: ["@vue/app", "@vue/babel-preset-jsx", "es2015"],
   plugins: ["@babel/plugin-proposal-object-rest-spread"]
 }

但是没有效果。那么,我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:1)

不需要为 JSX 设置 Babel,因为 Vue CLI 已经自动完成了。问题是您的 Vue CLI 项目需要配置为转译 Element UI,这可以通过 transpileDependencies config 来完成:

// vue.config.js
module.exports = {
  transpileDependencies: ['element-ui']
}

还要记住包含滑块的 CSS:

import ElSlider from 'element-ui/packages/slider/src/main.vue'
import 'element-ui/lib/theme-chalk/slider.css' ?