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.
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
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();
}
});