Simple way to use decorators with create-react-app

comments

By default, create-react-app doesn't supports decorators. Official position of Dan Abramov, maintainer of this library, is that decorators are not stable. They are in stage-2 at time of writing.

This position is understandable - decorators spec was changed with time and the best code - is not written code.

mobx without decorators

Although some libraries like mobx looks more usable with decorators, in fact you can live without decorators.

Because of decorators are just a syntax sugar, you can use them just like ordinary functions. Unfortunately, this looks ugly when you use more than one decorator and hard to support.

const person = observable({
    firstName: "Clive Staples",
    lastName: "Lewis"
});

In mobx v4 or v5, there is alternative decorate utility function API for that. The downside of this approach is human factor. There will be two places that need be edited and someone can forget about one of them.

class Person {
    firstName = "";
    lastName = "";
}
decorate(Person, {
    firstName: observable,
    lastName: observable
});
const person = new Person() {
    firstName: "Clive Staples",
    lastName: "Lewis"
}

If you do more googling you can find many articles which are enumerates options for plain javascript. They counts:

  • ejecting with npm run eject and then adding and using babel-plugin-transform-decorators-legacy babel plugin
  • alternative forks of create-react-app with decorators support
  • using babel macros (because macros are included in create-react-app)
  • use next.js which includes babel-plugin-transform-decorators-legacy babel plugin out of the box
  • using mobx's decorate utility function to avoid decorators usage

Found solution

But what if you'd like to stay with create-react-app and use mobx with decorators?

There is simple way you could get decorators support with create-react-app without ejecting or adding babel plugins - TypeScript to the resque! :) TypeScript has experimental support of decorators out of the box!

There is steps I've done to cure absence of decorators:

  1. Install TypeScript:

    # To create new React App project with TypeScript:
    npx create-react-app my-app --typescript
    # To add TypeScript to existing Create React App project
    npm i -S typescript @types/node @types/react @types/react-dom @types/jest
    
  2. Change extension of javascript files from *.js to *.ts and *.jsx to *.tsx

  3. Use experimentalDecorators: true in compilerOptions section in tsconfig.json

Now I can freely decorate my components and get some type checking and intellisense tooling support. And all with saved power of create-react-app's react-scripts, no pain with upgrades.

Happy coding!


If you like this post, consider supporting me on liberapay

Comments