VueJS。模块解析失败:意外的标记 <

VueJS. Module parse failed: Unexpected token <

我的一个 .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"]
 }

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

无需为 JSX 设置 Babel,因为 Vue CLI 已经自动完成了。问题是您的 Vue CLI 项目需要配置为转译元素 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'