当前位置: 首页> 文旅> 旅游 > react启用mobx @decorators装饰器语法

react启用mobx @decorators装饰器语法

时间:2025/8/23 15:38:27来源:https://blog.csdn.net/sinat_28071063/article/details/140326297 浏览次数:0次

react如果没有经过配置,直接使用decorators装饰器语法会报错:
Support for the experimental syntax ‘decorators’ isn’t currently enabled
在这里插入图片描述
因为react默认是不支持装饰器语法,需要做一些配置来启用装饰器语法。

step1:

在 tsconfig.json 中启用编译器选项 “experimentalDecorators”: true
vscode点击设置,输入搜索experimentalDecorators
在这里插入图片描述

step2:

安装支持修饰器所需依赖。

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

创建.babelrc文件,配置

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

安装依赖

yarn add -D customize-cra react-app-rewired

在项目根目录下创建 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())
step4:

修改package.json文件中 scripts 脚本。

"scripts": {"start": "react-app-rewired start","build": "react-app-rewired build","test": "react-app-rewired test","eject": "react-scripts eject"}

上面4个步骤配置完成后,如果mobx修饰器还是不起作用,就可能是mobx版本有问题,执行step5。

step5:

执行下面命令

yarn add -D mobx@5 mobx-react@5

执行到step5,就能成功使用mobx修饰器了。

注意,如果报错
Parsing error: Cannot use the decorators and decorators-legacy plugin together
在这里插入图片描述
可以创建.eslintrc.js文件,配置即可解决eslint报错问题

parserOptions: {parser: 'babel-eslint',ecmaFeatures: {// 支持装饰器legacyDecorators: true,},},

在这里插入图片描述

关键字:react启用mobx @decorators装饰器语法

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: