如何解决错误:当前未启用“jsx”

新手上路,请多包涵

我是 reactjs 的新手。我阅读了类似的错误帖子, Syntax Error: Support for the experimental syntax ‘jsx’ is not currently enabled but can’t solve my problem

当我运行 npm run dev

我有一个错误

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: -..../frontend/src/index.js: Support for the experimental syntax 'jsx' isn't currently enabled (40:7):

  38 |   render() {
  39 |     return (
> 40 |       <ul>
     |       ^
  41 |         {this.state.data.map(contact => {
  42 |           return (
  43 |             <li key={contact.id}>

Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

我读了这篇文章 Add @babel/preset-react 但我不明白我应该怎么做

webpack.config.js

 module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

索引.js

 import React, { Component } from 'react';
import { render } from "react-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loaded: false,
      placeholder: "Loading"
    };
  }

  componentDidMount() {
    fetch("api/lead")
      .then(response => {
        if (response.status > 400) {
          return this.setState(() => {
            return { placeholder: "Something went wrong!" };
          });
        }
        return response.json();
      })
     ...

原文由 swor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.7k
2 个回答

首先你需要运行 npm install --save-dev @babel/preset-react

这将安装 @babel/preset-react 包并将其添加到您的 package.json 文件中。

然后,您需要在 src 文件夹中创建一个 .babelrc 文件,并将以下内容粘贴到其中:

 {
  "presets": ["@babel/preset-react"]
}

在此之后,您可以再次运行 npm run dev

原文由 Dan Cantir 发布,翻译遵循 CC BY-SA 4.0 许可协议

对我来说,这个 https://stackoverflow.com/a/52693007/10952640 解决了。

TL;DR:您必须将 @babel/preset-react 安装为 devDep,并在 babel config 和 webback 上安装。

React 应用程序使用 Babel 转换为“常规”javascript,并使用 Webpack 捆绑到单个 js 文件。你必须设置一个“预设”,@babel/preset-react,以便那些理解 React 结构的人。

正如 Dan Cantir 所说,您必须先安装预设。

然后你必须在 .babelrc (或你用于 babel 配置的其他格式)上启用它。我的整个 .babelrc:

 {
    "presets": ["@babel/preset-env", **"@babel/preset-react**"]
}

最后你还必须在 webpack 配置文件中设置它(一些省略):

 (...)
module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        options: { presets: ['@babel/env', '@babel/preset-react'] },
      },
(...)

原文由 BetoLima1 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题