In this shot, we will learn how to create a React App with Webpack 5.
npm init -y
npm i react react-dom
npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader css-loader html-webpack-plugin sass sass-loader style-loader url-loader webpack webpack-cli webpack-dev-server
{"presets": ["@babel/preset-env", "@babel/preset-react"]}
const path = require("path");const HtmlWebpackPlugin = require("html-webpack-plugin");module.exports = {output: {path: path.join(__dirname, "/dist"), // the bundle output pathfilename: "bundle.js", // the name of the bundle},plugins: [new HtmlWebpackPlugin({template: "src/index.html", // to import index.html file inside index.js}),],devServer: {port: 3030, // you can change the port},module: {rules: [{test: /\.(js|jsx)$/, // .js and .jsx filesexclude: /node_modules/, // excluding the node_modules folderuse: {loader: "babel-loader",},},{test: /\.(sa|sc|c)ss$/, // styles filesuse: ["style-loader", "css-loader", "sass-loader"],},{test: /\.(png|woff|woff2|eot|ttf|svg)$/, // to import images and fontsloader: "url-loader",options: { limit: false },},],},};
/src
folder and create the following files inside it|-- src
|-- App.js
|-- App.scss
|-- index.html
|-- index.js
import React from "react";const App = () => {return <h1>Hello React</h1>;};export default App;
h1 {color: red;}
<!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 id="app"></div><!-- Notice we are pointing to `bundle.js` file --><script src="bundle.js"></script></body></html>
import React from "react";import ReactDOM from "react-dom";import App from "./App";import "./App.scss";const el = document.getElementById("app");ReactDOM.render(<App />, el);
serve
and build
scriptsIn your package.json
file, add the following:
{"name": "react-webpack","version": "1.0.0","description": "","main": "index.js","scripts": {"serve": "webpack serve --mode development","build": "webpack --mode production"},"keywords": [],"author": "","license": "ISC","dependencies": {"react": "^17.0.2","react-dom": "^17.0.2"},"devDependencies": {"@babel/core": "^7.15.0","@babel/preset-env": "^7.15.0","@babel/preset-react": "^7.14.5","babel-loader": "^8.2.2","css-loader": "^6.2.0","html-webpack-plugin": "^5.3.2","sass": "^1.38.1","sass-loader": "^12.1.0","style-loader": "^3.2.1","url-loader": "^4.1.1","webpack": "^5.51.1","webpack-cli": "^4.8.0","webpack-dev-server": "^4.0.0"}}
Run the app with npm run serve
.
Open your browser on http://localhost:3030/
.
Try to modify it and see the changes on the fly.
Run npm run build
in the terminal.
You will see the following output:
|-- dist
|-- bundle.js
|-- bundle.js.LICENSE.txt
|-- index.html
Finally, open the index.html file and you should see your app.