The Minimal React Project Setup using Webpack and Babel
Many starter kits are available for creating React projects. Starter kits are useful, but most of them are black boxes. They improve productivity once the developers have an understanding of how they work. For large-scale applications, we want to create the application from scratch and want full control over it.
This blog post aims to explain how to create a minimal React project using Webpack and Babel from scratch, step by step.
Step 1: Create a project folder and package.json file in the folder
mkdir react-minimal-project
cd react-minimal-project
npm init -y
Step 2: Install React and React DOM packages
npm install --save react react-dom
Step 3: Install Webpack, Webpack CLI, and Webpack Dev Server
npm install --save-dev webpack
npm install --save-dev webpack-cli
npm install --save-dev webpack-dev-server
Step 4: Install Babel
npm install --save-dev @babel/core babel-loader
npm install --save-dev @babel/preset-env @babel/preset-react
The
@babel/core
is the babel compiler. Thebabel-loader
is the webpack plugin for babel. The@babel/preset-env
is the Babel preset for converting ES6, ES7, and ES8 code to ES5. The@babel/preset-react
is the Babel preset for all React plugins.
Create the babel configuration file .babelrc
touch .babelrc
Add the following configuration to .babelrc
file.
.babelrc
{
"presets": "@babel/preset-env", "@babel/preset-react"]
}
Step 5: Create Webpack configuration file webpack.config.js
touch webpack.config.js
Step 6: Add the below configuration to webpack.config.js
file
webpack.config.js
module.exports = {
entry: './src/app',
output: {
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
Step 7: Let’s write a hello world React component
src/helloworld.js
import React, { Component } from 'react';
class HelloWorld extends Component {
render() {
return (<h1>Hello World, React!</h1>);
}
}
export default HelloWorld;
Step 8: Let’s display the <HelloWorld />
React component on the page using react-dom render() method
src/app.js
import React from 'react';
import { render } from 'react-dom';
import HelloWorld from './helloworld';
render(<HelloWorld />, document.getElementById('app-root'));
Step 9: Let’s create an index.html page to render our react application
index.html
Step 10: Let’s update the scripts section in the package.json file to run our application using the webpack dev server
"scripts": {
"start": "webpack-dev-server --mode development --open --hot"
}
Go to the project folder in the terminal and run npm start
command. This will start the webpack dev server, opens the browser, and display the result of <HelloWorld />
component.
You can find the sample code here.