Create a new directory for your project:
mkdir react-webpack-babel-example
cd react-webpack-babel-example
Initialize a new Node.js project using npm:
npm init -y
Install React, ReactDOM, Webpack, Babel, and necessary loaders:
npm install react react-dom
npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env @babel/preset-react html-webpack-plugin
Create a file named webpack.config.js
:
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
devServer: {
static: './dist',
port: 3000,
},
};
Create a file named .babelrc
:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
Create the following directories and files:
mkdir src
touch src/index.js src/index.html
Add basic content to src/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Webpack Babel Example</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
Add basic React code to src/index.js
:
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return <h1>Hello, React with Webpack and Babel!</h1>;
};
ReactDOM.render(<App />, document.getElementById('root'));
package.json
Modify the scripts
section of package.json
:
"scripts": {
"build": "webpack --mode production",
"start": "webpack serve --mode development"
}
Build the project:
npm run build
Start the development server:
npm start
Open your browser and navigate to http://localhost:3000
to see the application running.
create-react-app
CommandRun the following command:
npx create-react-app@latest my-app
Replace my-app
with your desired project name.
Change into the new project directory:
cd my-app
Start the development server:
npm start
Open your browser and navigate to http://localhost:3000
to see the default React application.