Ejecting and adding decorators to your create-react-app

If you are like me you’re probable in need of decorators on your create-react-app. There isn’t an easy and clean way to do it without ejecting the app so that is exactly what I’m going to go through on this post.

Step 1

npm run eject

You will notice that a couple folders showed up on your directory tree. One of them is /config which contains the Webpack file config we are looking for.

Step 2

Add transform decorators legacy babel plugin to your app

yarn add babel-plugin-transform-decorators-legacy

Add the bold line to /config/webpack.config.dev.js around line 162. Make sure to do the same on /config/webpack.config.prod.js otherwise the app won’t build

// Process JS with Babel.
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve(‘babel-loader’),
options: {
plugins: [‘transform-decorators-legacy’],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel- loader/
// directory for faster rebuilds.
cacheDirectory: true

Step 3

Now you can fully use decorators

import {withRouter} from ‘react-router’
class MyComponent extends …