React项目中使用装饰器报错

  • 在初次使用React 的装饰器时,第一次在项目中使用 @会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。
  1. 安装插件
  • yarn add -D react-app-rewired customize-cra
  • yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env
  1. 修改package.json文件中 scripts 脚本
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-app-rewired eject"
}
  1. 在项目根目录下创建 config-overrides.js 并写入以下内容
const path = require("path");
const { override, addDecoratorsLegacy } = require('customize-cra');
function resolve(dir) {
  return path.join(__dirname, dir);
}

const customize = ()=> (config, env)=> {
  config.resolve.alias['@'] = resolve('src')
  if(env === 'production') {
    config.externals = {
      'react': 'React',
      'react-dom': 'ReactDOM'
    }
  }
  return config;
}

module.exports = override(addDecoratorsLegacy(), customize())
  1. 在项目根目录下创建 .babelrc 并写入以下内容
{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ]
  ]
}
posted @ 2022-12-27 21:57  HuangBingQuan  阅读(46)  评论(0编辑  收藏  举报