Skip to content

Instantly share code, notes, and snippets.

@ludo
Forked from int128/README.md
Created May 3, 2019 15:44
Show Gist options
  • Save ludo/22bd7046b9377e70278d303dddac85b4 to your computer and use it in GitHub Desktop.
Save ludo/22bd7046b9377e70278d303dddac85b4 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.

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 webpackconfig = require('react-scripts/config/webpack.config.js')
const config = webpackconfig('development')
// removes react-dev-utils/webpackHotDevClient.js at first in the array
config.entry.shift()
config.entry = config.entry.filter(
entry => !entry.includes('webpackHotDevClient'),
)
config.output.path = paths.appBuild
paths.publicUrl = paths.appBuild + '/'
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,
})
}
@ludo
Copy link
Author

ludo commented May 3, 2019

Updated to work with CRA 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment