DEV Community

loading...
Cover image for React setup with webpack for beginners

React setup with webpack for beginners

deepanjangh profile image Deepanjan Ghosh Updated on ・6 min read

There are many ways to set up a react project and the popular ones you may hear of create-react-app and webpack. So today we'll see how to set up a react project with webpack and babel in a simple way.

So what is Webpack?

The definition says Webpack is a static module bundler for modern JavaScript applications and what do we mean by that?

Webpack is a bundler that bundles all the javascript files and internally it makes a dependencies graph that is responsible for mapping all your modules and depending on this graph it creates a bundle.js file that can be plugged into your HTML file.

So in this article, I want to show you how to set up your first react app with webpack and this will be a very minimal setup and afterward, you'll be able to extend the features depending on your needs.

1.Initial Phase (Folder Setup)

First, we'll start by creating a Project folder and then a public and src folder inside it. Public folder will be used to serve the application and this folder will be everything to publish your application. In the src folder, all the javascript files will be there and this folder will be bundled into a single javascript file and will be placed automatically in the public folder.

mkdir webpack-react
cd webpack-react
mkdir public src 
Enter fullscreen mode Exit fullscreen mode

Next, we'll create an index.html file inside the public folder with the following content.

cd public
touch index.html
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React with webpack</title>
</head>
<body>
    <div>
        <h1>Hello Webpack</h1>
    </div>
    <script src="./bundle.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. Setting up Webpack

Now before we start installing webpack and other npm packages we need to set up package.json first. Setting up package.json is easy either you can do it manually by running npm init by this you can fill in all the details by yourself or you can let npm handle it by simply adding -y at the end like npm init -y. This will create the package.json in the root folder.
Let's install some packages first and I'll explain each one by one.

npm i webpack webpack-cli webpack-dev-server --save-dev
Enter fullscreen mode Exit fullscreen mode
  • We need webpack to bundle all our javascript code to single and to build our application.
  • webpack-dev-server is needed to serve the application in the local web server for development purposes.
  • webpack-cli provides a flexible set of commands for developers to increase speed when setting up a custom webpack project.

(Note: Add a .gitignore file to avoid node_modules to push in git)

Let's add a start script now in package.json to run web-dev-server

...
    "start": "webpack serve --mode development"
...
Enter fullscreen mode Exit fullscreen mode

You can run npm start on your command line to start the application on your local server. Now let's generate bundle.js and see how we can bundle all the javascript code into a single file. Now we need to add a webpack configuration so now we will add webpack.config.js in the root folder.

touch webpack.config.js
Enter fullscreen mode Exit fullscreen mode

and update the start script in package.json.

...
start: "webpack serve --config ./webpack.config.js --mode development",
...
Enter fullscreen mode Exit fullscreen mode

Next, let's create an index.js file inside src where all the javascript code will be linked.

cd src
touch index.js
Enter fullscreen mode Exit fullscreen mode

and add a simple log inside it

console.log("Hello World")
Enter fullscreen mode Exit fullscreen mode

Now will add an entry point inside the webpack configuration to bundle in our case it is src/index.js and if index.js imports another javascript file it bundles them too.
The next step is to add an output file which will be bundle.js and this file is linked to the public/index.html and third step is to add a folder that will be used by the webpack dev server to serve our application to the browser. The content will look like this.

const path = require('path');

module.exports = {
  entry: path.resolve(__dirname, './src/index.js'),
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
  },
};
Enter fullscreen mode Exit fullscreen mode

(Note: path is used to resolve them properly across the operation system)

Now run npm start in your command line you'll see Hello World logged in your browser console.

Now we will add Babel to transpile back the modern javascript features (ES6 and others) to vanilla javascript. Let's install some packages for babel.

npm i @babel/core @babel/preset-env babel-loader --save-dev
Enter fullscreen mode Exit fullscreen mode
  • @babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s).
  • Loaders tell webpack how to interpret and translate files. The transformation happens on a per-file basis before adding to the dependency graph.

We need to add the babel in the build process in webpack.config.js. Your webpack.config.js will look like this.

const path = require('path');

module.exports = {
  entry: path.resolve(__dirname, './src/index.js'),
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js']
  },
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
  },
};
Enter fullscreen mode Exit fullscreen mode

(Note: module is added in which we have rules which will test all the .js file and exclude node_modules and will be using babel-loader for it)

Now let's add a babel configuration for that let's create a .babelrc file in the root folder and add the below configuration inside.

touch .babelrc
Enter fullscreen mode Exit fullscreen mode
{
  "presets": [
    "@babel/preset-env"
  ]
}
Enter fullscreen mode Exit fullscreen mode

3. React with webpack

Till now we have set up the webpack and babel configuration to successfully bundle our javascript code but react is not all javascript, therefore, we need to support react syntax which is the .jsx file. So we need babel again to transpile the code. Let's add some more dependencies for that

npm i @babel/preset-react --save-dev
Enter fullscreen mode Exit fullscreen mode

and also add the configuration to ./babelrc.

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Now we need to add rules in webpack.config.js to make jsx file transpile.

const path = require('path');

module.exports = {
  entry: path.resolve(__dirname, './src/index.js'),
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
  },
};
Enter fullscreen mode Exit fullscreen mode

Now we can write React with jsx code. Let's add the react packages and create a component.

npm i react react-dom --save
Enter fullscreen mode Exit fullscreen mode

Creating a Home component inside a component folder in src.

cd src
mkdir components
touch Home.jsx
Enter fullscreen mode Exit fullscreen mode

Home.jsx

import React from 'react';

const Home = () => {
return <div>React Application</div>
}

export default Home
Enter fullscreen mode Exit fullscreen mode

Update the src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Home from './components/Home';

ReactDOM.render(
  <Home />,
  document.getElementById('app')
);
Enter fullscreen mode Exit fullscreen mode

And at last, let's update the index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello React</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./bundle.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now run npm start again and you'll able to see the Home component render and there it is how you can set up react with webpack. Although this is a very basic setup, this will give you an idea of how to add more loader and plugin and set it up according to your needs. I'll be writing more about the advanced features and how to make it work with your webpack in the upcoming posts.

Don't forget to give a ❤️ if you liked it and thanks for reading. Happy coding!! 🖥

(Note: I have not shown how to use CSS with webpack, I will explain those step in a future post and will also share a boilerplate of react with webpack soon.)

(Update: The second part of this post is now available, where I have explained How to setup Styles (css and sass) with webpack.)

Discussion (5)

Collapse
carrotfarmer profile image
Dhruva Srinivas

Hey, nice tutorial, how would I be able to do this for a React app with TypeScript?

Collapse
deepanjangh profile image
Deepanjan Ghosh Author • Edited

Hey! thanks,
Well for now you need add some dev dependencies for typescripts, like you need to install npm i --save-dev typescript @types/react @types/react-dom awesome-typescript-loader and add a typescript configuration file like tsconfig.json.
Change the .jsx files to .tsx and you can find plenty of article explaining the setup of tsconfig.json.
Soon I'll also add a comprehensive post for typescript setup as well.

Collapse
carrotfarmer profile image
Dhruva Srinivas

Thank you!

Collapse
karinduboy profile image
Karin Duboy

OMG!!! thank you very much!
Really helpfull, precise, concise and updated...
Love it!!

Collapse
deepanjangh profile image
Forem Open with the Forem app