If you’re looking to bootstrap a React app, check out Create React App.
This article goes over how to build a React app with Webpack.
Problem
Given the package.json
:
{
"dependencies": {
"react": "17",
"react-dom": "17"
}
}
The index.html
:
<!-- index.html -->
<div id="root"></div>
<script src="dist/main.js"></script>
And src/index.js
:
// src/index.js
import React from 'react';
import { render } from 'react-dom';
function App(props) {
return <p>Hello, world!</p>;
}
render(<App />, document.getElementById('root'));
If you try to open the webpage:
open index.html
It fails because the browser doesn’t understand JSX. The code needs to be transpiled before it can be run. Webpack is a module bundler that can do that.
Dependencies
Install webpack
and webpack-cli
:
npm install webpack webpack-cli
Install babel-loader
, @babel/core
, and @babel/preset-env
:
npm install babel-loader @babel/core @babel/preset-env
To transpile JSX, install @babel/preset-react
:
npm install @babel/preset-react
Configuration
Create your webpack config:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
],
},
};
Build the webpack bundle:
npx webpack --mode=development
Open the webpage to see your app:
open index.html
To use the latest ECMAScript features, check out @babel/preset-env
.
Also, you can keep your Babel presets in .babelrc
:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
Which allows you to remove them from your webpack config:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
- options: {
- presets: ['@babel/preset-env', '@babel/preset-react'],
- },
},
},
],
},
};