Skip to content

Instantly share code, notes, and snippets.

@gonzofish
Last active April 6, 2018 18:44
Show Gist options
  • Save gonzofish/fc395f8caa11196b0bcca4411266ccc0 to your computer and use it in GitHub Desktop.
Save gonzofish/fc395f8caa11196b0bcca4411266ccc0 to your computer and use it in GitHub Desktop.
A webpack watch task through create-react-app & react-app-rewired

The below code will run a Webpack watch while leveraging create-react-app and react-app-rewired. The code is primarily based off of this gist but modified to work with react-app-rewired. Some of the comments on the original gist helped make this work.

Having a watch task like this is useful when you need to use your create-react-app-scaffolded code run through another server and not the Webpack dev server.

Usage

As in the original gist, add a task to your package.json that runs the script through node. Note that in the below, the script code is in a file at scripts/watch.js.

{
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "watch": "node ./scripts/watch.js"
  }
}

And run the script using:

npm run watch

The Script

process.env.NODE_ENV = 'development';

const { copySync } = require('fs-extra');
const paths = require('react-app-rewired/scripts/utils/paths');
const overrides = require('react-app-rewired/config-overrides');
const webpack = require('webpack');
const webpackConfigPath = paths.scriptVersion + '/config/webpack.config.dev';
const originalConfig = require(webpackConfigPath);
const config = overrides.webpack(
  originalConfig,
  process.env.NODE_ENV
);

const copyPublicFolder = () => {
  copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: (file) => file !== paths.appHtml,
  });
};

config.entry = config.entry.filter(
  (entry) => !entry.includes('webpackHotDevClient')
);
config.output.path = paths.appBuild;
paths.publicUrl = paths.appBuild + '/';

webpack(config).watch({}, (err) => {
  if (err) {
    console.error(err);
  } else {
    copyPublicFolder();
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment