【问题标题】:Support for the experimental syntax 'classProperties' isn't currently enabled当前未启用对实验语法“classProperties”的支持
【发布时间】:2019-02-13 17:04:28
【问题描述】:

我在 Django 项目中设置 React 时遇到了这个错误

ModuleBuildError 在 模块构建失败(来自 ./node_modules/babel-loader/lib/index.js): 语法错误:C:\Users\1Sun\Cebula3\cebula_react\assets\js\index.js:支持 对于实验性语法“classProperties”当前未启用 (17:9):

  15 | 
  16 | class BodyPartWrapper extends Component {
> 17 |   state = {
     |         ^
  18 | 
  19 |   }
  20 | 

Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 
'plugins' section of your Babel config to enable transformation.

所以,我安装了 @babel/plugin-proposal-class-properties 并将其放入 babelrc

package.json

{
  "name": "cebula_react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --config ./webpack.config.js --mode development",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config prod.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  },
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.2",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "react-hot-loader": "^4.3.6",
    "webpack": "^4.17.2",
    "webpack-bundle-tracker": "^0.3.0",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.8"
  },
  "dependencies": {
    "react": "^16.5.0",
    "react-dom": "^16.5.0"
  }
}

babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

但是错误依旧存在,请问是什么问题?

【问题讨论】:

  • 您不应该同时拥有/需要 @babel/plugin-proposal-class-propertiesbabel-plugin-transform-class-properties。你在安装后重建,是吗?
  • 你运行的是什么版本的 babel?
  • 分享你的json包
  • 我编辑了我的包 json
  • 尝试运行npx babel-upgrade --write --install

标签: reactjs webpack babeljs


【解决方案1】:

改变

"plugins": [
    "@babel/plugin-proposal-class-properties"
  ]

收件人

"plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]

这对我有用

【讨论】:

【解决方案2】:

首先安装:@babel/plugin-proposal-class-properties作为开发依赖:

npm install @babel/plugin-proposal-class-properties --save-dev

然后编辑您的 .babelrc,使其完全像这样:

{
  "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
  ],
  "plugins": [
      [
        "@babel/plugin-proposal-class-properties"
      ]
  ]
}

.babelrc 文件位于根目录,package.json 所在的位置。

请注意,您应该重新启动 webpack 开发服务器以使更改生效。

【讨论】:

  • 这个对我有用,谢谢。我认为是 babel 7.0+ 的解决方案
  • 在 IDE 中不适用于 React 18。React 应用程序确实可以工作,但每次在 IDE 中扫描文件时都会出现一个丑陋的错误。
  • React 17,也就是。
【解决方案3】:

webpack 项目解决方案

我只是通过在 webpack 配置插件中添加 @babel/plugin-proposal-class-properties 来解决这个问题。 我的webpack.config.js 的模块部分是这样的

module: {
    rules: [
        {
            test: path.join(__dirname, '.'),
            exclude: /(node_modules)/,
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env',
                          '@babel/react',{
                          'plugins': ['@babel/plugin-proposal-class-properties']}]
            }
        }
    ]
}

【讨论】:

  • 这应该是你使用 webpack 时的正确答案,因为有很多配置文件(如 webpack.config.js、package.json 和 .babelrc)并不好 - github.com/babel/babel/issues/8655#issuecomment-419795548
  • 完美地为我工作 - 对此我感到困惑好几天......非常感谢。
  • webpack.config.js 是哪一个?我目前得到 3 个。
【解决方案4】:
{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        [
          "@babel/plugin-proposal-class-properties"
        ]
    ]
}

用上面的代码替换你的 .babelrc 文件。它为我解决了这个问题。

【讨论】:

  • 如果你已经退出了 create-react-app,用这个配置更改 webpack.config.demo 和 package.json 中的任何配置。这意味着运行npm install --save-dev @babel/preset-env @babel/preset-react @babel/plugin-proposal-class-properties
  • 这很简单。碰巧我错过了@babel/plugin-proposal-class-properties 依赖项。
  • 它成功了,但请确保先安装@babel/plugin-proposal-class-properties
【解决方案5】:

在我的工作环境根目录中,.babelrc 文件不存在。但是,在 package.json 中的以下条目解决了这个问题。

"babel": {
"presets": [
  "@babel/preset-env",
  "@babel/preset-react"
],
"plugins": [
  "@babel/plugin-proposal-class-properties"
]}

注意:在执行 npm 或 yarn 命令之前,不要忘记退出控制台并重新打开。

【讨论】:

    【解决方案6】:

    有两种方法可以处理反应状态:

    选项 1: 只需添加到 package.json:

    "babel": {
            "presets": [
                "@babel/preset-env",
                "@babel/preset-react"
            ],
            "plugins": [
                "@babel/plugin-proposal-class-properties"
            ]
        }
    

    选项 2:

    1.在根文件夹中创建一个名为 .babelrc 的文件。

    写入.babelrc:

    { "plugins": ["@babel/plugin-proposal-class-properties"] }
    
    1. 运行:

    npm i @babel/plugin-proposal-class-properties

    3.运行:

    npm run dev
    or
    npm run watch
    

    【讨论】:

      【解决方案7】:

      在同一错误上搜索并花费了将近 3 个小时后,我发现我正在为 React 使用名称导入:

      import { React } from 'react';
      

      这是完全错误的。只需将其切换为:

      import React from 'react';
      

      所有错误都消失了。 我希望这可以帮助别人。这是我的 .babelrc:

      {
        "presets": [
          "@babel/preset-env",
          "@babel/preset-react"
        ],
        "plugins": [
            "@babel/plugin-proposal-class-properties"
        ]
      }
      

      webpack.config.js

      const path = require('path');
      const devMode = process.env.Node_ENV !== 'production';
      const MiniCssExtractPlugin = require('mini-css-extract-plugin');
      module.exports = {
        entry: './src/App.js',
        devtool: 'source-map',
        output: {
          path: path.resolve(__dirname, 'public'),
          filename: 'App.js'
        },
        mode: 'development',
        devServer: {
          contentBase: path.resolve(__dirname, 'public'),
          port:9090,
          open: 'google chrome',
          historyApiFallback: true
        },
        module: {
          rules: [
            {
              test: /\.m?js$/,
              exclude: /node_modules/,
              use: {
                loader: 'babel-loader'
              }
            },{
              test: /\.(sa|sc|c)ss$/,
              use: [
                devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
                {
                  loader: 'css-loader',
                  options: {
                    modules: true,
                    localIdentName: '[local]--[hash:base64:5]',
                    sourceMap: true
                  }
                },{
                  loader: 'sass-loader'
                }
              ]
            }
          ]
        },
        plugins: [
          new MiniCssExtractPlugin({
            filename: devMode ? '[name].css' : '[name].[hash].css',
            chunkFilename: devMode ? '[id].css' : '[id].[hash].css'
          })
        ]
      }
      

      package.json

      {
        "name": "expense-app",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "build": "webpack",
          "serve": "webpack-dev-server"
        },
        "author": "",
        "license": "ISC",
        "devDependencies": {
          "@babel/cli": "^7.1.2",
          "@babel/core": "^7.1.2",
          "@babel/plugin-proposal-class-properties": "^7.1.0",
          "@babel/preset-env": "^7.1.0",
          "@babel/preset-react": "^7.0.0",
          "babel-loader": "^8.0.4",
          "css-loader": "^1.0.0",
          "mini-css-extract-plugin": "^0.4.3",
          "node-sass": "^4.9.3",
          "react-router-dom": "^4.3.1",
          "sass-loader": "^7.1.0",
          "style-loader": "^0.23.1",
          "webpack": "^4.20.2",
          "webpack-cli": "^3.1.2",
          "webpack-dev-server": "^3.1.9"
        },
        "dependencies": {
          "normalize.css": "^8.0.0",
          "react": "^16.5.2",
          "react-dom": "^16.5.2"
        }
      }
      

      【讨论】:

      • 这个答案看起来与我无关。无论您使用什么插件,错误的导入都是错误的。
      • 感谢您的反馈@MarcoFaustinelli。错误的导入是此错误的原因之一。如此简单和基本的问题,但可能发生在每个人身上。答案是问题的指南。
      • 赞成不是因为它对我有用,而是因为它帮助我理解了问题所在 - 此错误消息不是很具体。
      【解决方案8】:

      我发现我的.babelrc 被忽略的问题,但是我创建babel.config.js 并添加以下内容:

      module.exports = {
        plugins: [
          ['@babel/plugin-proposal-decorators', { legacy: true }],
          ['@babel/plugin-proposal-class-properties', { loose: true }],
          '@babel/plugin-syntax-dynamic-import',
          '@babel/plugin-transform-regenerator',
          [
            '@babel/plugin-transform-runtime',
            {
              helpers: false,
              regenerator: true,
            },
          ],
        ],
        presets: [
          "@babel/preset-flow",
          'module:metro-react-native-babel-preset',
        ],
      };
      

      它适用于 React Native 应用程序,我认为这也将有助于 React 应用程序。

      【讨论】:

      • module.exports = { "presets": ["module:metro-react-native-babel-preset"], "plugins": ["@babel/plugin-proposal-class-properties"] } 对我来说已经足够了。你能更新你的答案吗?我们也应该明白为什么.babelrc被忽略了
      • @FabrizioBertoglio Babel 7 不再自动加载 .babelrc。 Babel 7 中的新功能是“根”目录的概念。对于项目范围的配置,Babel 会自动搜索“babel.config.js”
      【解决方案9】:

      constructor function 中移动state 对我有用:

      ...
      class MyComponent extends Component {
        constructor(man) {
          super(man)
          this.state = {}
        }
      }
      ...
      

      祝你好运……

      【讨论】:

        【解决方案10】:
        • 安装 plugin-proposal-class-properties npm install @babel/plugin-proposal-class-properties --save-dev

        • 通过添加更新您的 webpack.config.js 'plugins': ['@babel/plugin-proposal-class-properties']}]

        【讨论】:

        • 有关如何添加“插件”的更多信息,请参阅this page
        • 这样做会给我一个错误,类似于Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. - configuration.plugins[1] should be one of these: object { apply, … } | function -> Plugin of type object or instanceof Function Details: * configuration.plugins[1] should be an object. -> Plugin instance * configuration.plugins[1] should be an instance of function -> Function acting as plugin
        【解决方案11】:

        根据this GitHub 问题,如果您使用create-react-app,您应该将您的.babelrcbabel.config.js 配置复制到webpack.config.js 并删除那些。因为htis 两行代码babelrc: false,configFile: false, 您的配置在 babelrc 中,.. 没用。 并且您的 webpack.config.js 在您的 ./node_madules/react-scripts/config 文件夹中 我这样解决了我的问题:

        {
                      test: /\.(js|mjs)$/,
                      exclude: /@babel(?:\/|\\{1,2})runtime/,
                      loader: require.resolve('babel-loader'),
                      options: {
                        babelrc: false,
                        configFile: false,
                        compact: false,
                        presets: [
                          [
                            require.resolve('babel-preset-react-app/dependencies'),
                            { helpers: true },
        
                          ],
                          '@babel/preset-env', '@babel/preset-react'
                        ],
                        plugins: ['@babel/plugin-proposal-class-properties'],
                        .
                        .
                        .
        

        【讨论】:

        • 你是否在 react 脚本中编辑了 webpack 配置?那只会导致它在下一个 npm i 中被覆盖?然后应该弹出。
        • 我只是做了 GitHub 页面上提到的任何事情。当时解决了我的问题。
        【解决方案12】:

        我明确地使用了 babel 解析器。以上解决方案都不适合我。这行得通。

        const ast = parser.parse(inputCode, {
              sourceType: 'module',
              plugins: [
                'jsx',
                'classProperties', // '@babel/plugin-proposal-class-properties',
              ],
            });
        

        【讨论】:

        • 我应该在哪里添加此代码?你用 react js 吗?
        • 这段代码是如果你正在开发一个 babel 插件。是的,我的插件适用于 JSX。 github.com/Ghost---Shadow/i18nize-react
        【解决方案13】:

        我正在使用纱线。我必须执行以下操作才能克服错误。

        yarn add @babel/plugin-proposal-class-properties --dev
        

        【讨论】:

          【解决方案14】:

          添加

          "plugins": [
              [
                "@babel/plugin-proposal-class-properties"
              ]
            ]
          

          进入.babelrc 为我工作。

          【讨论】:

            【解决方案15】:

            yarn add --dev @babel/plugin-proposal-class-properties

            npm install @babel/plugin-proposal-class-properties --save-dev .babelrc

            【讨论】:

              【解决方案16】:

              对于弹出的 create-react-app 项目

              我刚刚解决了我的案例,将以下几行添加到我的webpack.config.js

                presets: [
                  [
                    require.resolve('babel-preset-react-app/dependencies'),
                    { helpers: true },
                  ],
                  /* INSERT START */
                  require.resolve('@babel/preset-env'),
                  require.resolve('@babel/preset-react'),
                    {
                    'plugins': ['@babel/plugin-proposal-class-properties']
                  } 
                  /* INSERTED END */
                ],
              

              【讨论】:

                【解决方案17】:

                如果有人在 react-native-web-monorepo 之后从事 monorepo 工作,那么您需要在 packages/web 中提交 config-overrides.js 文件。您需要在该文件中添加resolveApp('../../node_modules/react-native-ratings'),...

                我完整的config-override.js 文件是

                const fs = require('fs');
                const path = require('path');
                const webpack = require('webpack');
                
                const appDirectory = fs.realpathSync(process.cwd());
                const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
                
                // our packages that will now be included in the CRA build step
                const appIncludes = [
                    resolveApp('src'),
                    resolveApp('../components/src'),
                    resolveApp('../../node_modules/@react-navigation'),
                    resolveApp('../../node_modules/react-navigation'),
                    resolveApp('../../node_modules/react-native-gesture-handler'),
                    resolveApp('../../node_modules/react-native-reanimated'),
                    resolveApp('../../node_modules/react-native-screens'),
                    resolveApp('../../node_modules/react-native-ratings'),
                    resolveApp('../../node_modules/react-navigation-drawer'),
                    resolveApp('../../node_modules/react-navigation-stack'),
                    resolveApp('../../node_modules/react-navigation-tabs'),
                    resolveApp('../../node_modules/react-native-elements'),
                    resolveApp('../../node_modules/react-native-vector-icons'),
                ];
                
                module.exports = function override(config, env) {
                    // allow importing from outside of src folder
                    config.resolve.plugins = config.resolve.plugins.filter(
                        plugin => plugin.constructor.name !== 'ModuleScopePlugin'
                    );
                    config.module.rules[0].include = appIncludes;
                    config.module.rules[1] = null;
                    config.module.rules[2].oneOf[1].include = appIncludes;
                    config.module.rules[2].oneOf[1].options.plugins = [
                        require.resolve('babel-plugin-react-native-web'),
                        require.resolve('@babel/plugin-proposal-class-properties'),
                    ].concat(config.module.rules[2].oneOf[1].options.plugins);
                    config.module.rules = config.module.rules.filter(Boolean);
                    config.plugins.push(
                        new webpack.DefinePlugin({ __DEV__: env !== 'production' })
                    );
                
                    return config
                };
                

                【讨论】:

                  【解决方案18】:

                  我在尝试使用 babel 转换一些 jsx 时遇到了同样的问题。以下是对我有用的解决方案。您可以将以下 json 添加到您的 .babelrc

                  {
                    "presets": [
                      [
                        "@babel/preset-react",
                        { "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
                      ]
                    ],
                    "plugins": [["@babel/plugin-proposal-class-properties"]]
                  }
                  

                  【讨论】:

                    【解决方案19】:

                    对于带有 webpack 的 react 项目:

                    1. 执行:npm install @babel/plugin-proposal-class-properties --save-dev
                    2. 在存在package.jsonwebpack.config.js 的根文件夹中创建.babelrc(如果不存在)文件,并在其中添加以下代码:

                    {
                      "presets": ["@babel/preset-env", "@babel/preset-react"],
                      "plugins": [
                        [
                          "@babel/plugin-proposal-class-properties",
                          {
                            "loose": true
                          }
                        ]
                      ]
                    }
                    1. 将以下代码添加到webpack.config.js 文件中:

                    {
                                test: /\.jsx?$/,
                                exclude: /node_modules/,
                                loader: 'babel-loader',
                                query: {
                                    presets: ["@babel/preset-env", "@babel/preset-react"]
                                },
                                resolve: {
                                    extensions: ['.js', '.jsx']
                                }
                    }
                    1. 关闭终端并再次运行npm start

                    【讨论】:

                      【解决方案20】:

                      您必须安装

                      npm install @babel/core @babel/plugin-proposal-class-properties @babel/preset-env @babel/preset-react babel-loader

                      更改输入和输出


                      const path = require('path')        
                      module.exports = {
                        entry: path.resolve(__dirname,'src', 'app.js'),
                        output: {
                          path: path.resolve(__dirname, "public","dist",'javascript'),
                          filename: 'bundle.js'
                        },
                        module: {
                          rules: [
                            {
                              test: /\.(jsx|js)$/,
                              exclude: /node_modules/,
                              use: [{
                                loader: 'babel-loader',
                                options: {
                                  presets: [
                                    ['@babel/preset-env', {
                                      "targets": "defaults"
                                    }],
                                    '@babel/preset-react'
                                  ],
                                  plugins: [
                                    "@babel/plugin-proposal-class-properties"
                                  ]
                                }
                              }]
                            }
                          ]
                        }
                      }
                      

                      【讨论】:

                        【解决方案21】:

                        我为 src/components -> ../../components 创建了一个符号链接,导致 npm start 发疯并停止将 src/components/*.js 解释为 jsx,从而给出同样的错误。来自官方babel 的所有修复说明都是无用的。 当我复制回组件目录时,一切都恢复正常!

                        【讨论】:

                        • 你找到解决办法了吗?我有一个以正常方式安装的依赖项的应用程序,我可以对其进行测试,但是当我使用来自 yarn 链接的库时,它抛出了错误
                        • @mdsadiq 抱歉,没有,没有测试最新版本,票仍然在这里开放:github.com/facebook/create-react-app/issues/9040 也许你可以投票,谢谢。
                        【解决方案22】:

                        确保您没有错误地导入import BrowserRouter from "react-router-dom/modules/BrowserRouter"; 而不是import {BrowserRouter} from "react-router-dom";

                        【讨论】:

                          猜你喜欢
                          • 2020-03-06
                          • 2022-10-22
                          • 2021-04-26
                          • 2020-08-07
                          • 2019-11-10
                          • 1970-01-01
                          • 1970-01-01
                          • 2019-12-12
                          • 2020-02-09
                          相关资源
                          最近更新 更多