React with Webpack 5
As of July 2021, create-react-app
uses Webpack 4. Unfortunately, it means that we have to install dependancies and configure the build process ourselves to experiment with Webpack 5. This is a quick guide to migrate projects created with create-react-app
to Webpack 5.
1. Create a new project/Use existing one
npx create-react-app reactw5
2. Upgrade to Webpack 5
If you used create-react-app
to initialize the project, it handles bundling, transpililation and other optimizations for you out of the box. But this setup uses Webpack 4 and have no use to us with Webpack 5. We need to install Webpack 5 along with other tools and configure them.
Webpack dependancies
yarn add -D webpack webpack-cli webpack-dev-server html-webpack-plugin serve
Babel dependancies
yarn add -D babel-loader @babel/core @babel/preset-env @babel/preset-react
Loaders and plugins
yarn add -D css-loader style-loader @svgr/webpack style-loader url-loader
All this is just to configure everything that comes out of the box with create-react-app
It’s times like these I appreciate what it’s doing under the hood.
3. Create webpack.config.js
file in the root level.
Now that we have Webpack 5, we need a custom configuration to make it work.
*** This is by no means a production ready configuration. You might need to handle typescript, CSS pre/post processors and other optimizations based on your needs. But hopefully enough to get you started***
4. Create babel.config.json
file in the root level.
We installed a bunch of babel plugins to help us with React. Let’s configure them.
5. Finally, update package.json
file.
Now that we have configured Webpack and Babel, we need to replace our NPM scripts.
You should be able to start the application with yarn start
Your React app now uses webpack 5. Cheers!