【react】---react中使用装饰器

  • 运行 npm run eject 可以让由create-react-app创建的项目的配置项暴露出来

  • 此时,项目中多了一个config文件,并且各个配置文件已经暴露出来了。(运行npm run eject之前,保证本地没有待提交到git的文件)

  • 安装babel插件npm install --save-dev @babel/plugin-proposal-decorators react-app-rewired customize-cra react-scripts @babel/plugin-syntax-jsx @babel/helper-create-regexp-features-plugin

  • 修改package.json文件的scripts配置项

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

  • 修改package.json文件的babel配置项

    "babel": {
       "plugins": [
        ["@babel/plugin-proposal-decorators", { "legacy": true}]
      ],
       "presets": [
         "react-app"
      ]
    }
  • 在项目的根目录下创建config-overrides.js

    const{ override,addDecoratorsLegacy} =require('customize-cra');
    ​
    module.exports=override(
       addDecoratorsLegacy()
    );

  • 在项目的根目录下创建jsconfig.json

    {
       "compilerOptions": {
           "experimentalDecorators": true
      }
    }