Sunday, September 15, 2019

React create-react-app edit WebPack DevServer settings (adding SSL certificate options)

I have a React application that has been created with the create-react-app tool and I needed to change WebPack DevServer settings. Three the most popular suggestions I found on the internet were:
  • npm run eject
  • fork the react-scripts and make necessary changes
  • use a library like react-app-rewired
Unfortunately, all of them have various drawbacks (I will not discuss them here) and require too much effort. So finally, I found the simplest possible solution. The config file is here
'./node_modules/react-scripts/config/webpackDevServer.config.js'. Just edit the file here and that's it! For example, my task was to add an SSL certificate (.pfx). So for that I had to do 3 simple steps:
  1. Create a new folder security on the root app level and put the certificate file into it.
  2. Add the string HTTPS=true to the .env file. If you don't have the file, just create it on the root app level.
  3. Add the two options to the config file
Well, if you have another password for your certificate, update the pfxPassphrase field. If you have a different certificate type, the fields must be different. Reference to the official WebPack DevServer documentation, there is the entire option list https://webpack.js.org/configuration/dev-server/

But this solution has one drawback - the changes above are not saved when we delete node_modules folder and install everything from scratch with npm install.
I have found the simple fix for that - to make a script that overrides the config file when necessary.
  1. Create a new folder config on the root app level and copy the updated webpackDevServer.config.js file into it.
  2. Create a new script postInstall.js on the root app level and insert the following code inside it:
    const fs = require('fs');
    
    fs.copyFile(
        './config/webpackDevServer.config.js',
        './node_modules/react-scripts/config/webpackDevServer.config.js',
        err => {
            if (err) {
                console.error('Cannot copy webpackDevServer.config');
                console.error(err);
                throw err;
            }
    
            console.log('webpackDevServer.config is copied');
        }
    );
    
  3. Add the following line into the package.json file, scripts section: "post-install": "node ./postInstall.js"

So now, after npm install just run another command npm run post-install and that's it - your webpackDevServer.config file has been copied from the /config folder to the destination. Have a nice day!

No comments:

Post a Comment