Getting started in React with Webpack
Posted on 22nd March 2020
5 min read•
tl;dr - Clone and run the source code.
Usually when starting to work on a React project, developers go with create-react-app. While this is a great option for many cases, I find it to be a bit too bloated, especially after ejecting it. In this post I’ll show you how to setup a React project with Webpack. If you prefer to use the Parcel Bundler instead of webpack, check out my post here.
To start let’s initialize a project.
Then install the Webpack dependencies as dev dependencies.
After that let’s setup babel by installing the dev dependencies and creating the
Once the dependencies are done installing create the
.babelrc file in the project root with the following code.
Babel will allow us to use ES6+ feature in code without breaking the functionality for older browsers.
Next we need to configure babel to load all .js and .jsx files thorough the babel-loader. For that create the
webpack.config.js file in the project root and enter the following configuration.
First install react, react-dom and react-router-dom (which we will use for routing).
After that create the
index.js file in the
Next let’s create the root component in the
App.js file. The root component is going to contain the routing configuration.
After that let’s create a layout for our pages. Create the folder
src and in it create
Layout.js. The layout component is also going to contain the navigation links within the app.
Then let’s create the pages. In
src create a folder called
pages. The first page we are going to create is the home page.
After that we will create the about page.
Connecting to a HTML file
Install html-webpack-plugin and html-loader as dev dependencies.
Then update the webpack config.
After that create the HTML file,
index.html in the
Finally update the
Webpack development server
If you want to run the project in the development mode you’ll need the webpack-dev-server dependency.
Next add the dev script in
Then all you need to start the development server is the following command.
To get the production build of the project which is optimized add these scripts to
To serve the production build let’s use the serve dependency.
build- Will get build the production version of the project.
start- Will start the app.
When you visit
localhost:5000 in your browser after running
npm start, you should be seeing
When you navigate to “About” you should see
Now you can continue creating your React app as usual from here. The source code for everything done here is available in GitHub.
If you enjoyed this post please leave a like or two below!!!
Check out my latest post...Making delayed network requests in React after state changes
13th September 2021