Webpack is a static module bundler for JavaScript applications that allows you to bundle your JavaScript files, images, fonts, and stylesheets into one or multiple bundles.
Here’s the step-by-step guide for how to use Webpack with React.js:
Step 1: Node.js Installation
Make sure you have Node.js and npm installed. If not, you can download it from https://nodejs.org.
Step 2: Initializing a New Project
Create a new folder for your project, navigate into it and run the command:
```
npm init -y
```
This command generates a new ‘package.json’ file in your project.
Step 3: Install React and React-DOM
Run the command:
```
npm install react react-dom —save
```
This will install React and ReactDOM to your project and add them to your ‘package.json’ file.
Step 4: Install Babel
Install the Babel presets and plugins with the command:
```
npm install babel/core babel-loader
babel/preset-env @babel/preset-react —save-dev
```
Babel is used to transpile ES6 and JSX into ES5.
Step 5: Install Webpack
Install Webpack and the webpack-dev-server in your project with the command:
```
npm install webpack webpack-cli webpack-dev-server html-webpack-plugin —save-dev
```
- webpack-dev-server: Provides live reloading during development.
- html-webpack-plugin: Simplifies the creation of HTML files to serve your webpack bundles.
Step 6: Setting up Babel and Webpack
Add a ‘.babelrc’ file to the root of your project, and put the following lines of code into it:
```
{
“presets”: [“@babel/preset-env”, “@babel/preset-react”]
}
```
Create a ‘webpack.config.js’ file in your root directory. Here is a sample configuration:
```
const HtmlWebpackPlugin = require(‘html-webpack-plugin’);
const path = require(‘path’);
module.exports = {
entry: ‘./src/index.js’,
output: {
path: path.resolve(__dirname, ‘dist’),
filename: ‘index_bundle.js‘
},
module: {
rules: [
{test: /\.(js|jsx)$/, exclude: /node_modules/, use: ‘babel-loader’},
{test: /\.css$/, use: [‘style-loader’, ‘css-loader’]}
]
},
plugins: [
new HtmlWebpackPlugin({template: ‘src/index.html’})
]
}
```
Step 7: Edit ‘package.json’ file
Update ‘scripts’ field in package.json:
```
“scripts”: {
“start”: “webpack serve —mode development —open —hot”,
“build”: “webpack —mode production“
},
```
Now you can use the command npm run start for development and npm run build for production.
Step 8: Creating React Components
Now, you are ready to build your React component files in the ‘src’ folder.
Note: Don’t forget to install and include your CSS loader if you are using CSS. You can do it with:
```
npm install style-loader css-loader —save-dev
```
The webpack configuration can vary based on the project’s requirement. You can customize it as needed. Different loaders and plugins are available which can be used with webpack.