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



我的一个.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项目需要配置为编译Element UI,这可以通过transpileDependencies配置完成:

// 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' 👈

最新更新