Skip to content

Instantly share code, notes, and snippets.

@intentionally-left-nil
Forked from jasonblanchard/README.md
Last active February 22, 2018 07:14
Show Gist options
  • Save intentionally-left-nil/26ba4f858b93989c6ea980f21868f0c4 to your computer and use it in GitHub Desktop.
Save intentionally-left-nil/26ba4f858b93989c6ea980f21868f0c4 to your computer and use it in GitHub Desktop.
Watching build mode on Create React App

Create React App does not provide watching build mode oficially (#1070).

This script provides watching build mode for an external tool such as Chrome Extensions or Firebase app. You can either build the dev bundle once with build:dev, or continually rebuild it with watch

How to Use

Create a React app.

Put the script into scripts/build.js.

Add build:dev and watch tasks into the scripts block in package.json as follows:

  "scripts": {
    "start": "react-scripts start",
    // Add next line
    "build:dev": "node scripts/build.js",
    "watch": "npm run build:dev --watch",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }

Run the watch task.

npm run watch

Change source code and check build output.

Directory structure may be following:

  • app/
    • src/
    • public/
    • scripts/
      • watch.js (need to add)
    • package.json (need to modify)
    • build/ (output)
process.env.NODE_ENV = 'development';
const fs = require('fs-extra');
const paths = require('react-scripts/config/paths');
const webpack = require('webpack');
const config = require('react-scripts/config/webpack.config.dev.js');
let entry = config.entry;
let plugins = config.plugins;
entry = entry.filter(fileName => !fileName.match(/webpackHotDevClient/));
plugins = plugins.filter(plugin => !(plugin instanceof webpack.HotModuleReplacementPlugin));
config.entry = entry;
config.plugins = plugins;
// set the output location to /build to match prod
config.output.path = paths.appBuild;
// Determine if we want to build or watch
const watch = process.argv[2] === '--watch';
const compiler = webpack(config);
watch ? compiler.watch({}, buildCallback) : compiler.run(buildCallback);
function buildCallback(err, stats) {
if (err) {
console.error(err);
} else {
copyPublicFolder();
}
console.error(stats.toString({
chunks: false,
colors: true
}));
}
function copyPublicFolder() {
console.log(`copying files ${paths.appPublic}, ${paths.appBuild}`);
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment