SoFunction
Updated on 2025-04-07

Detailed explanation of how to enable the decorator syntax in create-react-app version 2.0

create-react-app (cra for short) has been updated in version 2.0.3, and babel has also been updated to version. Although the JavaScript decorator syntax is not standard, with the help of babel, you can also enjoy playing in the project.

How to enable the decorator syntax in the cra2.0 era? We still usereact-app-rewired, by hijacking webpack comfig objects, the purpose of modification is achieved.

yarn add react-app-rewired

Revise

"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test"
 }

Install the babel plug-in required for decorator syntax, and you can also upgrade babel-core

yarn add @babel/plugin-proposal-decorators metro-react-native-babel-preset -D

Create .babelrc, file in the project root directory

// .babelrc
{
 "presets": ["module:metro-react-native-babel-preset"],
 "plugins": [
  [
   "@babel/plugin-proposal-decorators",
   {
    "legacy": true
   }
  ]
 ]
}

// config-overrides
const { getBabelLoader } = require('react-app-rewired');

const path = require('path');

 = function override(config, env) {
 const babelLoader = getBabelLoader();
 const pwd = ();
  = [(`${pwd}/src`)];
 // use babelrc
  = true;
 
 return config;
};

The principle is to hijack the config object and make simple modifications to its babel rules.

Attached the complete

{
 "name": "my-react-project",
 "version": "0.1.0",
 "private": true,
 "dependencies": {
  "react": "^16.5.2",
  "react-app-rewired": "^1.6.2",
  "react-dom": "^16.5.2",
  "react-scripts": "2.0.5"
 },
 "scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test"
 },
 "eslintConfig": {
  "extends": "react-app"
 },
 "browserslist": [
  ">0.2%",
  "not dead",
  "not ie <= 11",
  "not op_mini all"
 ],
 "devDependencies": {
  "@babel/plugin-proposal-decorators": "^7.1.2",
  "metro-react-native-babel-preset": "^0.48.1",
  "webpack-bundle-analyzer": "^3.0.3"
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.