使用 create-react-app 初始化的项目,能满足大多数情况下的需求,但是想用装饰器等比较新的技术时,你可能会去创建一个.babelrc 文件,然后配置成如下操作
安装
npm i -D @babel/plugin-proposal-decorators
配置 .babelrc
{
"plugins": ["@babel/plugin-proposal-decorators", { "legacy": true }],
}
然后,你惊奇的发现,依然无效!!
What!!!
源代码走起!!
打开 node_modules/react-scrpts/config/webpack.config.js
,搜索 babelrc
可以看到,配置babel处理 js 文件时,直接禁用了使用 babelrc
想使用 .babelrc?
Tweak the create-react-app webpack config(s) without using ‘eject’ and without creating a fork of the react-scripts.
All the benefits of create-react-app without the limitations of “no config”. You can add plugins, loaders whatever you need.
安装
npm i -D react-app-rewired customize-cra
配置:项目根目录下创建 config-overrides.js
/* config-overrides.js */
const { useBabelRc, override } = require('customize-cra')
const config = override(useBabelRc())
module.exports = config
这样就启用了 .babelrc 配置文件,装饰器就可以用起来了
另外如果仅仅想使用装饰器,可以不用创建 babelrc 文件
通过阅读 customize-cra 源码
发现直接这样配置也可以