在初次使用React 的装饰器时,第一次在项目中使用 @ 会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。
查了很多资料终于彻底解决,下面我将列出如何给装饰器打好前战!
基础:create-react-app
如果没有创建react项目后面都是徒劳啦。
npx create-react-app demo
创建好项目之后才能进行后续操作。
- 首先,安装插件
"devDependencies": {
"@babel/core": "^7.10.5",
"@babel/plugin-proposal-decorators": "^7.10.5",
"@babel/preset-env": "^7.10.4",
"customize-cra": "^1.0.0",
"http-proxy-middleware": "^1.0.5",
"react-app-rewired": "^2.1.6"
}
- 在
package.json
中修改scripts
的运行属性值
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
- 在项目的根目录下新建一个
config-overrides.js
文件(文件名一定不要写错,因为会根据这个文件名进行编译代码)
// 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())
基本完成上面这三步就可以正常使用装饰器了,再也不会报 @
的错误了。同时Support for the experimental syntax 'decorators-legacy' isn't currently enabled
这个错误也将消失。
引入装饰器后续问题
1. 解决函数名飘红问题
在引入装饰器之后,虽然不会报错,但是下面的函数名还是会有飘红,这时需要进行一些相应的设置。
解决方案:
打开设置 => 在搜索栏输入 decorator
找到全称为 JavaScript › Implicit Project Config: Experimental Decorators
的设置项,将其勾选上,保存即可。