React项目中使用装饰器报错
- 在初次使用React 的装饰器时,第一次在项目中使用 @会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。
- 安装插件
- yarn add -D react-app-rewired customize-cra
- yarn add -D @babel/core @babel/plugin-proposal-decorators @babel/preset-env
- 修改package.json文件中 scripts 脚本
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
}
- 在项目根目录下创建 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())
- 在项目根目录下创建 .babelrc 并写入以下内容
{
"presets": [
"@babel/preset-env"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
本文作者:HuangBingQuan
本文链接:https://www.cnblogs.com/bingquan1/p/17009111.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2021-12-27 fetch
2021-12-27 Vue生命周期