See GitHub
https://github.com/jsramblings/react-webpack-setup
See reference
https://jsramblings.com/creating-a-react-app-with-webpack/
Set up
mkdir react-webpack
cd react-webpack
npm init -y
npm install webpack webpack-cli --save-dev
npm install html-webpack-plugin --save-dev
npm install --save-dev webpack-dev-server
Directory structure
- public
- index.html
- src
- App.jsx
- index.js
webpack.config.js
.babelrc
package.json
// index.html
<!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 + Webpack</title>
</head>
<body>
<h1>Hello React + Webpack!</h1>
<div id="root"></div>
</body>
</html>
// index.js
import React from "react";
import { createRoot } from "react-dom/client";
import Hello from "./Hello";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(<Hello />);
// src/Hello.jsx
const Hello = () => <h1>Hello from React!</h1>;
export default Hello;
// webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "build"),
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "public", "index.html"),
}),
],
devServer: {
static: {
directory: path.join(__dirname, "build"),
},
port: 3000,
}
};
// package.json
{
"name": "react-webpack-setup",
"version": "1.0.0",
"description": "Simple step by step walkthrough of setting up a React app with Webpack",
"main": "index.js",
"scripts": {
"build": "webpack --mode production",
"start": "webpack serve --mode development"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jsramblings/react-webpack-setup.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/jsramblings/react-webpack-setup/issues"
},
"homepage": "https://github.com/jsramblings/react-webpack-setup#readme",
"devDependencies": {
"@babel/core": "^7.18.2",
"@babel/preset-env": "^7.18.2",
"@babel/preset-react": "^7.17.12",
"babel-loader": "^8.2.5",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.73.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.1"
},
"dependencies": {
"react": "^18.1.0",
"react-dom": "^18.1.0"
}
}
// .babelrc
{
"presets": ["@babel/preset-react"]
}
// webpack-config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.ts",
module: {
rules: [{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
}, ],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "public", "index.html")
})
],
devServer: {
static: {
directory: path.join(__dirname, "build"),
},
port: 3000
},
}