Is it possible to use decorators with create-react-app?

Viewed 2642

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?

2 Answers

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)
);

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"]
}
Related