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