175

While I was setting up React within Django project I came across this error

ModuleBuildError in Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C:\Users\1Sun\Cebula3\cebula_react\assets\js\index.js: Support for the experimental syntax 'classProperties' isn't currently enabled (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.

So, I installed @babel/plugin-proposal-class-properties and put this in 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"
  ]
}

However the error is still existed, What is the problem??

6
  • You shouldn't have/need both @babel/plugin-proposal-class-properties and babel-plugin-transform-class-properties. You're rebuilding after install, yes?
    – SamVK
    Commented Sep 8, 2018 at 18:04
  • What version of babel are you running?
    – SamVK
    Commented Sep 8, 2018 at 18:06
  • share you package json Commented Sep 8, 2018 at 18:19
  • I edited my package json
    – 1Sun
    Commented Sep 9, 2018 at 1:38
  • try running npx babel-upgrade --write --install
    – FDisk
    Commented Feb 25, 2020 at 18:13

23 Answers 23

114

Change

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

To

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

This worked for me

6
91

First install the: @babel/plugin-proposal-class-properties as dev dependency:

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

Then edit your .babelrc so it will be exact like this:

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

.babelrc file located in the root directory, where package.json is.

Note that you should re-start your webpack dev server to changes take affect.

4
  • 4
    this one works for me, thanks. I think is the solution for babel 7.0+
    – Black Hole
    Commented May 31, 2019 at 3:15
  • Doesn't work for me in the IDE, with React 18. The React app does work, but there's an ugly error every time the file is scanned in the IDE. Commented Feb 6, 2021 at 10:34
  • React 17, that is. Commented May 9, 2021 at 8:04
  • I am new to the react dev. How I can re-start webpack dev server? I run npm start but this solution does not work for me? Commented Jun 22, 2022 at 12:51
75

Solution for webpack project

I just solve this problem by adding @babel/plugin-proposal-class-properties into webpack config plugin. The module section of my webpack.config.js looks like this

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']}]
            }
        }
    ]
}
4
  • 3
    This should be the proper answer when you use webpack, as it is not good to have many configuration files (like webpack.config.js, package.json, and .babelrc) - github.com/babel/babel/issues/8655#issuecomment-419795548
    – Miro J.
    Commented May 2, 2019 at 16:38
  • 1
    worked for me perfectly - was mystified on this for days...thanks much. Commented Aug 16, 2020 at 16:13
  • Which one is that webpack.config.js? I get 3 currently. Commented Apr 20, 2021 at 14:50
  • @BurakKaymakci You should have only one webpack.config.js in react root folder
    – BetoLima1
    Commented Jun 1, 2022 at 19:32
48
{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        [
          "@babel/plugin-proposal-class-properties"
        ]
    ]
}

replace your .babelrc file with above code. it fixed the issue for me.

3
  • If you have ejected create-react-app, change any config in webpack.config.demo and package.json with this config. This means running npm install --save-dev @babel/preset-env @babel/preset-react @babel/plugin-proposal-class-properties
    – hodgef
    Commented Nov 17, 2018 at 2:09
  • This was straight-forward. It so happened that I was missing the @babel/plugin-proposal-class-properties dependency.
    – khwilo
    Commented Jul 24, 2019 at 13:29
  • it worked, but make sure to install @babel/plugin-proposal-class-properties first
    – Minh Kha
    Commented Sep 25, 2020 at 4:16
20

In my work environment root, .babelrc file was not there. However, following entry in package.json solved the issue.

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

Note: Don't forget to exit the console and reopen before executing the npm or yarn commands.

8

There are two ways to work with react state:

Option 1: Just add to package.json:

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

Option 2:

1. Creta a file called .babelrc in the root folder.

Write in .babelrc:

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

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

3. Run:

npm run dev
or
npm run watch
7

After almost 3 hours of searching and spending time on the same error, I found that I'm using name import for React:

import { React } from 'react';

which is totally wrong. Just by switching it to:

import React from 'react';

all the error are gone. I hope this helps someone. This is my .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'
    })
  ]
}

the 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"
  }
}
3
  • This answer looks irrelevant to me. A wrong import is a wrong import, regardless of the plugins you're using. Commented Nov 7, 2018 at 10:07
  • thanks for your feedback @MarcoFaustinelli . A wrong import is one of the reasons of this error. So simple and fundamental problem but can happen to everyone. An answer is guide to a problem.
    – Mo Hemati
    Commented Nov 9, 2018 at 2:02
  • Upvoted not because it worked for me, but because it helped me understand what the problem was - this error message is not very specific.
    – Pro Q
    Commented Feb 1, 2019 at 1:20
7

Moving the state inside the constructor function worked for me:

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

Good Luck...

6
  • Install the plugin-proposal-class-properties npm install @babel/plugin-proposal-class-properties --save-dev

  • Update your webpack.config.js by adding 'plugins': ['@babel/plugin-proposal-class-properties']}]

2
  • For more information about how to add in the 'plugins', see this page
    – Pro Q
    Commented Feb 1, 2019 at 1:29
  • 1
    Doing this is giving me an error along the lines of 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
    – Pro Q
    Commented Feb 1, 2019 at 2:21
6

I find the problem that my .babelrc was ignored, However I create babel.config.js and add the following:

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

And it works for me on React Native application, I think this also would help React apps as well.

3
  • 1
    module.exports = { "presets": ["module:metro-react-native-babel-preset"], "plugins": ["@babel/plugin-proposal-class-properties"] } was enough for me. Can you update your answer and also we should understand why .babelrc was ignored Commented Mar 22, 2019 at 9:10
  • 1
    @FabrizioBertoglio Babel 7 no longer automatically loads .babelrc. New to Babel in 7, is the concept of a "root" directory. For project-wideconfiguration, Babel will automatically search for a "babel.config.js" Commented Mar 22, 2019 at 12:02
  • 1
    thanks .. babeljs.io/docs/en/config-files/#6x-vs-7x-babelrc-loading Commented Mar 22, 2019 at 12:49
5

According to this GitHub issue if you using create-react-app you should copy your .babelrc or babel.config.js configurations to webpack.config.js and delete those.because of htis two line of code babelrc: false,configFile: false, your config in babelrc,.. are useless. and your webpack.config.js is in your ./node_madules/react-scripts/config folder I solved my problem like this:

{
              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'],
                .
                .
                .
2
  • Did you edit the webpack config in react scripts? That will just cause it to be overwritten in the next npm i? Then should eject.
    – Tosh
    Commented Feb 19, 2021 at 12:37
  • I just did whatever on the GitHub page mention. at that time solved my problem.
    – Z-Soroush
    Commented Mar 11, 2021 at 17:18
4

I am using the babel parser explicitly. None of the above solutions worked for me. This worked.

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

I'm using yarn. I had to do the following to overcome the error.

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

Adding

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

into .babelrc works for me.

3

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

or

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

3

For ejected create-react-app projects

I just solved my case adding the following lines to my 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 */
  ],
1

If some one working on monorepo following react-native-web-monorepo than you need to config-overrides.js file in packages/web. you need to add resolveApp('../../node_modules/react-native-ratings'), in that file...

My complete config-override.js file is

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
};
1

I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc

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

For the react projects with webpack:

  1. Do: npm install @babel/plugin-proposal-class-properties --save-dev
  2. Create .babelrc (if not present) file in the root folder where package.json and webpack.config.js are present and add below code to that:

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

  1. Add below code to the webpack.config.js file:

{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ["@babel/preset-env", "@babel/preset-react"]
            },
            resolve: {
                extensions: ['.js', '.jsx']
            }
}

  1. Close the terminal and run npm start again.
1

you must install

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

and

change entry and output


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"
            ]
          }
        }]
      }
    ]
  }
}
1

If this happens after typescript update, just add useDefineForClassFields: false to tsconfig file.

See: https://www.typescriptlang.org/tsconfig#useDefineForClassFields

1
  • This resolved the problem in my case, but like you said the error started happening after I updated typescript. Commented Jan 12 at 21:18
0

I created a symlink for src/components -> ../../components that caused npm start to go nuts and stop interpreting src/components/*.js as jsx, thus giving that same error. All instructions to fix it from official babel were useless. When I copied back the components directory everything was BACK TO NORMAL!

3
  • 1
    did you find any solution to this ? i have a application with dependencies installed in normal fashion and i am able to test it, But when i use the lib from yarn link, it was throwing above error
    – mdsadiq
    Commented Oct 3, 2020 at 18:57
  • 1
    @mdsadiq sorry, no, haven't tested the latest ver and the ticket is still open here: github.com/facebook/create-react-app/issues/9040 maybe you can upvote, thanks.
    – martin
    Commented Oct 6, 2020 at 0:17
  • A workaround to allow react-scripts to work with symlinks: github.com/facebook/create-react-app/pull/7993/files
    – CefBoud
    Commented Jan 3, 2022 at 9:40
0

Ensure you have not mistakenly imported import BrowserRouter from "react-router-dom/modules/BrowserRouter"; instead of import {BrowserRouter} from "react-router-dom";

Not the answer you're looking for? Browse other questions tagged or ask your own question.