【问题标题】:ReactJS - Module build failed: SyntaxError: Unexpected token react components not renderingReactJS - 模块构建失败:SyntaxError: Unexpected token react components not rendering
【发布时间】:2017-11-02 13:46:21
【问题描述】:

我返回一个这样的反应组件:

return (
    <section style={styleObj} id="Profile" >
      <h2 className="colorHeader">{this.state.color}</h2>
      <input id="colorInput" placeholder="Enter Hex Code Here" onChange={this.changeColor.bind(this)}/>
      <div id="slider"></div>
    </section>
  );

这导致:

ERROR in ./app/js/modules/colorpicker.js
Module build failed: SyntaxError: Unexpected token (31:4)

  29 |
  30 |   return (
> 31 |     <section style={styleObj} id="Profile" >
     |     ^
  32 |       <h2 className="colorHeader">{this.state.color}</h2>
  33 |       <input id="colorInput" placeholder="Enter Hex Code Here" onChange={this.changeColor.bind(this)}/>
  34 |       <div id="slider"></div>

据我目前的理解,您需要一个 babel 转译器来正确转换它。我的 webpack 配置的相关部分如下所示:

module: {
  rules: [{
      test: /\.js$/,
      use: 'babel-loader'
    }]
  },

我做了更多的研究并尝试了这个:

loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        query  :{
          presets:['react','es2015']
        }
        exclude: /node_modules/
      }
    ]

这会返回:

模块构建失败:错误:找不到预设的“反应”相对于 目录

So I referenced this question and tried this:

{
  "presets": ["es2015", "react"]
}

还是得到:

模块构建失败:错误:找不到预设的“反应”相对于 目录

如何让 react 组件使用 webpack 配置正确呈现?

链接的答案建议npm ls babel-preset-es2015 得到:

new_platform_prototype@1.0.0 /projects/new-platform-prototype └── babel-preset-es2015@6.24.1

【问题讨论】:

标签: javascript reactjs babeljs


【解决方案1】:
npm install -D babel-preset-react babel-preset-es2015

这应该可以解决您的问题。

【讨论】:

    【解决方案2】:
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        query  :{
          presets:['react','es2015']
        }
        exclude: /node_modules/
      }
    ]
    

    尝试将 jsx 更改为 js

      loaders: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        query  :{
          presets:['react','es2015']
        }
        exclude: /node_modules/
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 2017-12-06
      • 2016-04-09
      • 2017-08-18
      • 2017-06-18
      相关资源
      最近更新 更多