Search code examples
vue.jsjsxbabel-loader

VueJS. Module parse failed: Unexpected token <


One of my .vue scripts has this import statement:

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

The problem is, when it compiles, it throws an error:

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>

As you can see, the source code contains these lines:

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

And it seems, that Vue by default does not like this syntax. I tried to specify a loader in vue.config.js like so:

   ...
   chainWebpack: config => {

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

But it does not help. If it matters, I also modified babel.config.js. So it now looks like:

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

But it has no effect. So, what am I doing wrong and how can I fix it?


Solution

  • There's no need to setup Babel for JSX, as Vue CLI already does that automatically. The problem is your Vue CLI project needs to be configured to transpile Element UI, which could be done with the transpileDependencies config:

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

    Also remember to include the CSS for the slider:

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