目前未启用对实验语法“ classProperties”的支持


117

当我在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"
  }
}

巴贝尔

{
  "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

分享您的json包
Sakhi Mansoor

我编辑了包裹json
1Sun

尝试运行npx babel-upgrade --write --install
FDisk

Answers:


81

更改

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

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

这对我有用


17
npm i --save-dev @ babel / plugin-proposal-class-properties
Abhay Shiro

1
这对我没用。我不是弹出反应应用
Supriya Kalghatgi

4
Ubuntu的18 -我不得不重新命名.babelrc,以babel.config.js和使用module.exportstackoverflow.com/questions/53916434/...在github上所讨论的github.com/babel/babel/issues/7879#issuecomment-419732313
法布里奇奥Bertoglio

2
Test suite failed to run; .loose is not a valid Plugin property
大卫·卡兰南

43

Webpack项目解决方案

我只是通过添加@babel/plugin-proposal-class-properties到webpack配置插件来解决此问题。我的模块部分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)不是很好-github.com/babel/babel/issues/8655# issuecomment-419795548
Miro

非常适合我-为之迷惑了好几天...非常感谢。
samuelsaumanchan

42

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

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开发服务器,以使更改生效。


2
这对我有用,谢谢。我认为这是babel 7.0+的解决方案
黑洞

1
这对我有用。
Bhimashankar Sutar

36
{
    "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
Francisco Hodge

这很简单。碰巧我错过了@babel/plugin-proposal-class-properties依赖性。
khwilo

11

在我的工作环境根目录中,.babelrc文件不存在。但是,在package.json中输入以下内容即可解决此问题。

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

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


6

经过将近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"
  }
}

这个答案对我来说似乎无关紧要。不管您使用的是什么插件,错误的导入都是错误的导入。
Marco Faustinelli,

感谢您的反馈@MarcoFaustinelli。导入错误是此错误的原因之一。如此简单和根本的问题,但可能会发生在每个人身上。答案是解决问题的指南。
Mo Hemati

支持不是因为它对我有用,而是因为它帮助我了解了问题所在-此错误消息不是很具体。
Pro Q

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

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


有关如何在“插件”添加更多的信息,请参阅本页面
临Q

这样做是给我一个错误的线沿线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
临Q

5

我发现我的问题.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

@FabrizioBertoglio Babel 7不再自动加载.babelrc。Babel 7中的新功能是“根”目录的概念。对于项目范围的配置,Babel将自动搜索“ babel.config.js”
Hussam Kurd


5

我刚刚在Laravel Framework 5.7.19上进行了测试,以下步骤可以正常工作:

确保您的.babelrc文件位于应用程序的根文件夹中,并添加以下代码:

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

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

运行npm run watch


4

我正在显式使用babel解析器。以上解决方案均不适用于我。这工作了。

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

我应该在哪里添加此代码?你用react js?
MoHammaD ReZa DehGhani,

1
此代码是在开发babel插件时使用的。是的,我的插件适用于JSX。github.com/Ghost---Shadow/i18nize-react
Souradeep Nanda

4

根据这个 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'],
                .
                .
                .

4

移动state内部constructor function为我工作:

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

祝好运...


3

我在用纱。我必须执行以下操作来克服该错误。

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

3

新增中

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

.babelrc了我的作品。


2

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

要么

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


1

如果某些人在react-native-web- monorepo之后从事monorepo的工作,则需要在中config-overrides.js提交packages/web。您需要添加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
};

0

我为src / components创建了一个符号链接-> ../../components,这使人发疯,npm start并停止将src / components / *。js解释为jsx,因此也出现了同样的错误。官方babel修复它的所有指令都没有用。当我复制回components目录时,一切都恢复了正常!


0

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

{
  "presets": [
    [
      "@babel/preset-react",
      { "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
    ]
  ],
  "plugins": [["@babel/plugin-proposal-class-properties"]]
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.