在初次使用React 的装饰器时,第一次在项目中使用 @ 会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。
查了很多资料终于彻底解决,下面我将列出如何给装饰器打好前战!
如果没有创建react项目后面都是徒劳啦。
1 npx create-react-app demo
创建好项目之后才能进行后续操作。
- 首先,安装插件
1 "devDependencies": { 2 "@babel/core": "^7.10.5", 3 "@babel/plugin-proposal-decorators": "^7.10.5", 4 "@babel/preset-env": "^7.10.4", 5 "customize-cra": "^1.0.0", 6 "http-proxy-middleware": "^1.0.5", 7 "react-app-rewired": "^2.1.6" 8 }
- 在
package.json
中修改scripts
的运行属性值
1 "scripts": { 2 "start": "react-app-rewired start", 3 "build": "react-app-rewired build", 4 "test": "react-app-rewired test", 5 "eject": "react-scripts eject" 6 },
- 在项目的根目录下新建一个
config-overrides.js
文件(文件名一定不要写错,因为会根据这个文件名进行编译代码)
1 // config-overrides.js 内容 2 const path = require('path') 3 const { 4 override, 5 addDecoratorsLegacy 6 } = require('customize-cra') 7 8 function resolve(dir) { 9 return path.join(__dirname, dir) 10 } 11 12 const customize = () => (config, env) => { 13 config.resolve.alias['@'] = resolve('src') 14 if (env === 'production') { 15 config.externals = { 16 'react': 'React', 17 'react-dom': 'ReactDOM' 18 } 19 } 20 21 return config 22 } 23 24 module.exports = override(addDecoratorsLegacy(), customize())
基本完成上面这三步就可以正常使用装饰器了,再也不会报 @
的错误了。同时Support for the experimental syntax 'decorators-legacy' isn't currently enabled
这个错误也将消失。
在引入装饰器之后,虽然不会报错,但是下面的函数名还是会有飘红,这时需要进行一些相应的设置。
打开设置 => 在搜索栏输入 decorator
找到全称为 JavaScript › Implicit Project Config: Experimental Decorators
的设置项,将其勾选上,保存即可。