首页 > 其他分享 >React项目中使用装饰器报错

React项目中使用装饰器报错

时间:2022-12-27 22:11:53浏览次数:33  
标签:react babel app React 报错 config 装饰 rewired

  • 在初次使用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
      }
    ]
  ]
}

标签:react,babel,app,React,报错,config,装饰,rewired
From: https://www.cnblogs.com/bingquan1/p/17009111.html

相关文章