您好,欢迎访问一九零五行业门户网

react 装饰器报错怎么办

react装饰器报错的解决办法:1、通过“create-react-app mobx-study”创建项目;2、通过“yarn add -d react-app-rewired customize-cra”安装插件;3、修改package.json文件中scripts脚本;4、在项目根目录下创建“config-overrides.js”和“.babelrc”即可。
本教程操作环境:windows10系统、react18.0.0版、dell g3电脑
react 装饰器报错怎么办?
react的decorators装饰器报错
一、decorators装饰器报错@
在初次使用react 的装饰器时,第一次在项目中使用 @
会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。
【报错显示:parsing error: this experimental syntax requires enabling one of the following parser plugin(s): “decorators-legacy”, “decorators”.】
1. 创建项目
npm install -g create-react-app  // 安装create-react-app,已安装请忽略create-react-app mobx-study
2. 安装插件 —— 改变 create-react-app 中 webpack 配置
yarn add -d react-app-rewired customize-cra yarn add -d @babel/core @babel/plugin-proposal-decorators @babel/preset-env
3. 修改package.json文件中 scripts 脚本
// package.jsonscripts: {    start: react-app-rewired start,    build: react-app-rewired build,    test: react-app-rewired test,    eject: react-scripts eject  }
4. 在项目根目录下创建 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())
5. 在项目根目录下创建 .babelrc 并写入以下内容
{ "presets": [ "@babel/preset-env" ], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ] ]}
基本完成以上步骤就可以正常使用装饰器了,再也不会报 @ 的错误了。同时support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled这个错误也将消失。
二、对修饰器的实验支持功能在将来的版本中可能更改。在 “tsconfig” 或 “jsconfig” 中设置 “experimentaldecorators” 选项以删除此警告。ts(1219)
设置 => 搜索experimentaldecorators => 打上勾勾
推荐学习:《react视频教程》
以上就是react 装饰器报错怎么办的详细内容。
其它类似信息

推荐信息