Skip to content

Instantly share code, notes, and snippets.

@int128 int128/README.md
Last active Jan 9, 2020

Embed
What would you like to do?
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.

How to Use

Create a React app.

Put the script into scripts/watch.js.

Add watch task into the scripts block in package.json as follows:

  "scripts": {
    "start": "react-scripts start",
    // Add next line
    "watch": "node scripts/watch.js",
    "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');
// removes react-dev-utils/webpackHotDevClient.js at first in the array
config.entry.shift();
webpack(config).watch({}, (err, stats) => {
if (err) {
console.error(err);
} else {
copyPublicFolder();
}
console.error(stats.toString({
chunks: false,
colors: true
}));
});
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml
});
}
@harrygr

This comment has been minimized.

Copy link

harrygr commented Aug 1, 2017

Looks good, but does not update PUBLIC_URL in the generated html when the app root is non-root. I.e. when homepage is set in package.json. Any idea how to make this work?

@tomaswitek

This comment has been minimized.

Copy link

tomaswitek commented Aug 14, 2017

Hi @harrygr,
I had the same problem, so I thought I'll post an answer here in case somebody has also this kind of problem.
The main reason is that it's importing dev config const config = require('react-scripts/config/webpack.config.dev.js'); which hardcodes publicUrl='/'.

What helped me was overriding publicPath right before the webpack watch call:

config.output.publicPath = process.env.PUBLIC_URL;

webpack(config).watch({}, (err, stats) => {
...
@amaurymartiny

This comment has been minimized.

Copy link

amaurymartiny commented Nov 17, 2017

In the current CRA (1.4.3), console.log(config.entry) gives me:

[ '/Users/amaurymartiny/Workspace/myapp/node_modules/react-scripts/config/polyfills.js',
  '/Users/amaurymartiny/Workspace/myapp/node_modules/react-dev-utils/webpackHotDevClient.js',
  '/Users/amaurymartiny/Workspace/myapp/src/index.js' ]

So the lines 8 and 9 don't do what they were supposed to do anymore. My proposal would be to change lines 8&9 to:

// removes react-dev-utils/webpackHotDevClient.js
config.entry = config.entry.filter(
  entry => !entry.includes('webpackHotDevClient')
);
@percyhanna

This comment has been minimized.

Copy link

percyhanna commented Dec 12, 2017

I had to make the following changes to get it working for me:

config.entry = config.entry.filter(
  entry => !entry.includes('webpackHotDevClient')
);

config.output.path = paths.appBuild;
paths.publicUrl = paths.appBuild + '/';
@gonzofish

This comment has been minimized.

Copy link

gonzofish commented Apr 6, 2018

thanks for doing this! and thanks to everyone's comments! it got me up and running

@ItamarShDev

This comment has been minimized.

Copy link

ItamarShDev commented Jun 20, 2018

Has anyone managed to get true Hot Reload with the build process?

@mycocodev

This comment has been minimized.

Copy link

mycocodev commented Jul 4, 2018

thanks @int128 for this Gist, and thanks @percyhanna, your changes works for me 😄

@ymyqwe

This comment has been minimized.

Copy link

ymyqwe commented Jul 5, 2018

Great job, helped me a alot. More job need to be done to fit with this requirement.

@ackvf

This comment has been minimized.

Copy link

ackvf commented Aug 10, 2018

This won't work with typescript though... 😞

@charlee

This comment has been minimized.

Copy link

charlee commented Sep 8, 2018

Thanks @int128 for the great script!
and thanks @percyhanna, your change fixed the issue that static dir goes out of build

@zzacharo

This comment has been minimized.

Copy link

zzacharo commented Sep 19, 2018

Anyone can provide a final working code because I am having some issues...

@Leo7654

This comment has been minimized.

Copy link

Leo7654 commented Sep 23, 2018

I think this is not best but it helps.
https://www.npmjs.com/package/npm-watch

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "watch:build": "npm-watch build",
    "eject": "react-scripts eject"
  },
  "watch": {
    "build": {
      "patterns": [
        "."
      ],
      "ignore": "build",
      "extensions": "*",
      "quiet": false
    }
  }
@francescovenica

This comment has been minimized.

Copy link

francescovenica commented Dec 9, 2018

this is a cool script but I notice that css is not updated...I'm the only one with this problem?for css I use scss and these 2 scripts:

    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",

I'm running watch-css in paralles

@rachelthecodesmith

This comment has been minimized.

Copy link

rachelthecodesmith commented Jan 8, 2019

Recent update to react-scripts, there's now only one file, 'react-scripts/config/webpack.config.js' you can give it the env as a parameter.

e.g.

const webpackconfig = require('react-scripts/config/webpack.config.js');

const config = webpackconfig('development');
@BalavigneshJ

This comment has been minimized.

Copy link

BalavigneshJ commented May 22, 2019

This watch.js worked for me.

process.env.NODE_ENV = 'development';

const fs = require('fs-extra');
const paths = require('react-scripts/config/paths');
const webpack = require('webpack');
const importCwd = require('import-cwd');
const config = importCwd('react-scripts/config/webpack.config')('production')

var entry = config.entry;
var plugins = config.plugins;

entry = entry.filter(fileName => !fileName.match(/webpackHotDevClient/));
plugins = plugins.filter(plugin => !(plugin instanceof webpack.HotModuleReplacementPlugin));

config.entry = entry;
config.plugins = plugins;

webpack(config).watch({}, (err, stats) => {
  if (err) {
    console.error(err);
  } else {
    copyPublicFolder();
  }
  console.error(stats.toString({
    chunks: false,
    colors: true
  }));
});

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

This comment has been minimized.

Copy link

brymon68 commented Jun 4, 2019

Has anyone been successful in changing paths.appBuild to a directory outside of the project root? For instance, I need to build to something like /opt/app/files/ on the host machine.

@cikandin

This comment has been minimized.

Copy link

cikandin commented Jul 24, 2019

If you use this script with customize-cra, you can add this line to script

const overrides = require('./config-overrides') // correct this line to your config-overrides path
overrides.webpack(config, process.env.NODE_ENV)
@vaas-montenegro

This comment has been minimized.

Copy link

vaas-montenegro commented Aug 21, 2019

overrides.webpack(config, process.env.NODE_ENV)

Can you give me a full example
This is my config-overrides file
`const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
addLessLoader({
javascriptEnabled: true,
modifyVars: {
'@primary-color': '#2e5bff' ,
'@text-color' : '#2e384d'
},
}),
);`

@mojtabaasadi

This comment has been minimized.

Copy link

mojtabaasadi commented Jan 9, 2020

my problem is that it can not find modules and looks for them in the src folder

ERROR in ./src/App.js
Module not found: Error: Can't resolve 'react' in '/var/www/pricewatch/src'
 @ ./src/App.js 2:0-26 7:9-14 14:5-10 21:5-10 30:6-11 36:14-19 42:45-50
 @ ./src/index.js
 @ multi ./src/index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.