当前未启用对实验性语法"classProperties"的支持。

174

在我将React集成到Django项目中时,遇到了以下错误:

ModuleBuildError:模块构建失败(来自./node_modules/babel-loader/lib/index.js): SyntaxError: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。你安装后重新构建了吗? - SamVK
你正在运行哪个版本的Babel? - SamVK
分享你的 package.json 文件。 - Sakhi Mansoor
我编辑了我的 package json。 - 1Sun
尝试运行 npx babel-upgrade --write --install - FDisk
@FDisk,这个不起作用。 - secondman
23个回答

114

更改

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

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

这对我起作用了


29
安装@babel/plugin-proposal-class-properties插件,命令为npm i --save-dev @babel/plugin-proposal-class-properties。 - Abhay Shiro
4
这对我没用。我无法弹出React应用程序。 - Supriya Kalghatgi
5
Ubuntu 18 - 我不得不将 .babelrc 重命名为 babel.config.js,并像 https://dev59.com/yLDma4cB1Zd3GeqPALOS 上在 GitHub 讨论的那样使用 module.export。这是针对 https://github.com/babel/babel/issues/7879#issuecomment-419732313 的解决方案。 - Fabrizio Bertoglio
2
Test suite failed to run; .loose is not a valid Plugin property - David Callanan
1
@DavidCallanan 要解决这个问题,只需删除第二个参数 ({"loose": true})。 - kugo2006
似乎不再起作用了:“无效的配置对象。Webpack已经使用与API模式不匹配的配置对象进行初始化。” - feeela

90

首先将@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 开发服务器才能使更改生效。


4
这个对我有用,谢谢。我认为这是解决 Babel 7.0+ 的方案。 - Black Hole
在我的IDE中无法工作,使用React 18。React应用程序确实可以工作,但每次在IDE中扫描文件时都会出现一个丑陋的错误。 - Juha Untinen
React 17,就是这样。 - Juha Untinen
我是 React 开发新手。我该如何重新启动 Webpack 开发服务器?我运行 npm start,但这个方法对我不起作用。 - Elham Bagheri

73

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']}]
            }
        }
    ]
}

3
当你使用webpack时,这应该是正确的答案,因为拥有多个配置文件(如webpack.config.js、package.json和.babelrc)并不好。- https://github.com/babel/babel/issues/8655#issuecomment-419795548 - Miro J.
完美地为我工作了 - 我对此感到困惑了好几天...非常感谢。 - samuelsaumanchan
那个 webpack.config.js 是哪一个?我目前有三个。 - Burak Kaymakci
@BurakKaymakci,你应该在react根目录中只有一个webpack.config.js文件。 - BetoLima1

48
{
    "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 - hodgef
这很简单。恰好我缺少了@babel/plugin-proposal-class-properties依赖项。 - khwilo
它有效了,但请确保首先安装@babel/plugin-proposal-class-properties。 - Minh Kha

19

在我的工作环境里,没有.babelrc文件。然而,在package.json中加入下面的条目解决了这个问题。

"babel": {
"presets": [
  "@babel/preset-env",
  "@babel/preset-react"
],
"plugins": [
  "@babel/plugin-proposal-class-properties"
]}
注意:在执行npm或yarn命令之前,请不要忘记退出控制台并重新打开。

8

有两种方法处理React状态:

选项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"
  ]
}

the 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"
  }
}

这个答案对我来说看起来不相关。无论你使用的插件是什么,错误的导入都是错误的导入。 - Marco Faustinelli
感谢您的反馈@MarcoFaustinelli。错误的导入是此错误的原因之一。如此简单而基本的问题,但每个人都可能会遇到。答案是解决问题的指南。 - Mo Hemati
点赞不是因为它对我有用,而是因为它帮助我理解了问题所在 - 这个错误信息并不是很具体。 - Pro Q

7
state移动到构造函数内对我起了作用。
...
class MyComponent extends Component {
  constructor(man) {
    super(man)
    this.state = {}
  }
}
...

祝你好运...


6
  • 安装plugin-proposal-class-properties插件 npm install @babel/plugin-proposal-class-properties --save-dev

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


有关如何添加“插件”的更多信息,请参见此页面 - Pro Q
这样做会给我带来一个错误,大致是`无效的配置对象。Webpack已经使用不符合API模式的配置对象进行了初始化。
  • configuration.plugins[1]应该是以下之一: object { apply, … } | function ->类型为对象或Function的插件 详情:
    • configuration.plugins[1]应该是一个对象。 ->插件实例
    • configuration.plugins[1]应该是函数的实例 ->作为插件的函数`
- Pro Q

6
我发现我的 .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应用程序。


1
module.exports = { "presets": ["module:metro-react-native-babel-preset"], "plugins": ["@babel/plugin-proposal-class-properties"] }这对我来说已经足够了。您可以更新您的回答,并且我们应该了解为什么.babelrc被忽略了。 - Fabrizio Bertoglio
1
@FabrizioBertoglio Babel 7不再自动加载.babelrc文件。在Babel 7中,引入了“根”目录的概念。对于项目范围的配置,Babel将自动搜索“babel.config.js”文件。 - Hussam Kurd
1
感谢。。。https://babeljs.io/docs/en/config-files/#6x-vs-7x-babelrc-loading - Fabrizio Bertoglio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接