Reputation: 1244
I have understood that since Babel doesn't support decorators out of the box (because it's in early stages of definition) create-react-app doesn't support it as well.
I know that you can eject the generated app and configure Babel to support them, but I don't want to do that.
Finally, libraries like MobX allow you to use decorator's behavior without actually using them, with the help of some utility functions like described at https://mobx.js.org/best/decorators.html
Is there something similar for React?
Upvotes: 10
Views: 3970
Reputation: 4182
In my case, it was a combination of plugins
To enable config customization
To enable decorators
npm install reflect-metadata --save-dev
import 'reflect-metadata'
in index.jsUpdate configs
babel
config from package.jsonconfig-overrides.js
file in project rootconst { addDecoratorsLegacy, override } = require('customize-cra') module.exports = override(addDecoratorsLegacy())
scrips
section in package.json
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject" },
Upvotes: 0
Reputation: 15985
It is also possible to use decorators with create-react-app by adding tsconfig.json file to the project that means enabling support for typescript.
You need to set experimentalDecorators
to true
in compiler options of tsconfig.json
Hope we are aware the .js and .tsx files can co-exist, so whichever file we want to use decorators we can convert to .tsx rest can remain .js files
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"noImplicitThis": false,
"experimentalDecorators": true, //<----
"types": ["cypress"]
},
"include": ["src"]
}
Upvotes: 0
Reputation: 17654
Yes, you can, but you need a couple of things,
Make sure you have react-app-rewired and customize-cra installed so you can override webpack and babel configs
install @babel/plugin-proposal-decorators
and update your config-overrides.js
file :
const { override, addBabelPlugin } = require("customize-cra");
const pluginProposalDecorators = require("@babel/plugin-proposal-decorators");
module.exports = override(
addBabelPlugin(pluginProposalDecorators)
);
Upvotes: 7