【问题标题】:VueJS. Module parse failed: Unexpected token <VueJS。模块解析失败:意外的令牌 <
【发布时间】:2021-04-26 21:13:43
【问题描述】:

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

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

【问题讨论】:

    标签: vue.js jsx babel-loader


    【解决方案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' ?
    

    【讨论】:

    • 谢谢,你为我指出了另一个依赖项的相同问题的正确方向:vue-meta。刚刚添加了vue-meta 而不是element-ui 并构建了:)
    猜你喜欢
    • 2019-02-15
    • 2023-03-27
    • 2021-05-01
    • 2020-11-16
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多