Making webpack and CRA emit files in watch mode

Viewed 2177

I'm, trying to make CRA's start script to emit files on changes instead of keeping them in memory.

I'm working to implement Google Chrome Extension so I need files to be flushed to the file system so that Chrome could pick them up. And building each change is not as convenient as an automatic compilation.

I've tried to use react-app-rewired to override a bunch of props in webpack config, including mode, watch, and to see 'output.path' but no luck so far.

Or CRA's 'start' script will never emit underlying because the loaders are not tuned to do that?

Appreciate your help!

2 Answers

You may need CRACO.

Create React App Configuration Override is an easy and comprehensible configuration layer for create-react-app.

$ npm install @craco/craco --save

Create a craco.config.js file in the root directory and configure CRACO:

my-app
├── node_modules
├── craco.config.js
└── package.json

Update package.json:

/* package.json */

"scripts": {
-   "start": "react-scripts start",
+   "start": "craco start",
-   "build": "react-scripts build",
+   "build": "craco build"
-   "test": "react-scripts test",
+   "test": "craco test"
}

Finally, edit craco.config.js file:

module.exports = {
  devServer: (devServerConfig) => {
    devServerConfig.writeToDisk = true;
    return devServerConfig;
  },
};

I know this question is already answered and yeah a couple of months ago this worked for me as well

but recently I started a new project where I wanted to couple a react app with express and I tried using the same setup and suddenly got the error below:

Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'writeToDisk'. These properties are valid:
   object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
error Command failed with exit code 1.

Since this QA has helped me back then I decided to share what I found here for anyone who is reading this in future and is getting the same error.

Solution

There seems to be some changes to webpack config "devserver" structure which you can find here: https://webpack.js.org/configuration/dev-server/

Where you can not use writeToDisk directly anymore and need to put it in a devMiddleware object like below:


    module.exports = {
        devServer: {
            devMiddleware: {
                writeToDisk: true,
            },
        },
        //...
    }

I am using: craco: ^6.4.3

I hope this helps someone who faced the same issue as me

Related