Customizing create_react_app without ejecting

As you might be aware the create_react_app is all the new hotness these days. While it eliminates the need for complex boilerplate, it leaves little room to for customization. We are in a weird fix where we have to use our react app within a Rails view. The layout belongs to Rails but we want to host the react app within it. However, the create-react-app assumes (rightly so) that it would be used in an independent static project.

I would like to use that without running an npm run eject on the project. All we needed was to generate a manifest as a part of the build so that we can use that to change references to the CSS and JS tags in the layout. Fortunately there exists a webpack plugin called the webpack-manifest-plugin for doing precisely that. So we wrote a build script that uses that and placed it in script/build.js within the react repo.

process.env.NODE_ENV = 'production'

var webPackProd = require('react-scripts/config/webpack.config.prod');
var ManifestPlugin = require('webpack-manifest-plugin');

webPackProd.plugins = [new ManifestPlugin()].concat(webPackProd.plugins);

require('react-scripts/scripts/build');

We then changed package.json to run this script instead of the standard react-scripts build for the npm run build command.

{
  "name": "newreactapp",
  "version": "0.0.1",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.6.1"
  },
  "dependencies": {
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "webpack-manifest-plugin": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "node ./scripts/build.js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Voila. Now when we have a manifest.json in our build directory that looks a bit like this.

{
  "main.css": "static/css/main.9a0fe4f1.css",
  "main.css.map": "static/css/main.9a0fe4f1.css.map",
  "main.js": "static/js/main.247a9e3c.js",
  "main.js.map": "static/js/main.247a9e3c.js.map",
  "static/media/logo.svg": "static/media/logo.5d5d9eef.svg"
}

Of course this is a hack and would not work very well if the structure of the template changes. I would really like more knobs and dials to configure create-react-app than the current all or nothing approach.

Advertisements

2 thoughts on “Customizing create_react_app without ejecting”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s