twiz
twiz

Reputation: 10558

Make Webpack DevServer write to disk in development environment with `create-react-app`'s

I have a project that was created with create-react-app and has been "ejected". For my use-case, I need to update the Webpack config to output files to the ./build directory in the development environment, like it does in production.

I added a devServer property to my config:

devServer: {
    writeToDisk: true,
}

and I updated the output property to have a path in the development environment:

// I changed this:
output: {
    path: isEnvProduction ? paths.appBuild : undefined,
    ...
}

// To this:
output: {
    path: paths.appBuild,
    ...
}

When I run yarn start, no files are written to the build directory.

What should I be doing differently?

Upvotes: 1

Views: 2596

Answers (1)

twiz
twiz

Reputation: 10558

The problem is that create-react-app doesn't setup webpack-dev-server using the devServer property of config/webpack.config.js.

Instead, it uses the webpack-dev-server directly in scripts/start.js with the following code:

const createDevServerConfig = require("../config/webpackDevServer.config");

// ...

const serverConfig = createDevServerConfig(
    proxyConfig,
    urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, (err) => {
    // ...
}

In other words, to alter the behavior of the DevServer, you should be updating config/webpackDevServer.config instead of setting the devServer property in config/webpack.config.js.

In this case, I just needed to add the writeToDisk property:

module.exports = function (proxy, allowedHost) {
    return {
        writeToDisk: true,
        //...
    }
}

This will cause the output files to be written to ./dist by default. To set a different directory, it is still necessary to also update output.path in config/webpack.config.js:

output: {
    path: paths.appBuild,
    ...
}

Upvotes: 2

Related Questions