欢迎来到码农权的博客 MaNongGeGe.|

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
      }
    ]
  ]
}

本文作者:HuangBingQuan

本文链接:https://www.cnblogs.com/bingquan1/p/17009111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   HuangBingQuan  阅读(57)  评论(0编辑  收藏  举报
历史上的今天:
2021-12-27 fetch
2021-12-27 Vue生命周期
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 不将就 码农权
  2. 2 Bleeding Love 码农权
  3. 3 想你念你 码农权
Bleeding Love - 码农权
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available