react项目中使用装饰器

326 阅读1分钟

首先安装babel转换器

yarn add  @babel/core @babel/preset-env @babel/plugin-proposal-decorators -D
npm i @babel/core @babel/preset-env @babel/plugin-proposal-decorators -D

在你的react根目录下创建.babelrc文件写入

{
    "presets": [
      "@babel/preset-env"
    ],
    "plugins": [
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
        }
      ]
    ]
  }

安装react-app-rewiredreact项目服务启动脚本

yarn add react-app-rewired -D

修改packjson.json的脚本配置 image.png 安装react--app-rewired支持的一个插件

yarn add customize-cra -D

写入装饰器装换的配置文件, 文件名固定不能改变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())

然后正常启动服务就行

yarn start