Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Webpack with Frameworks

Webpack with React

Set up webpack for a React app: babel-loader with preset-react, the automatic JSX runtime, CSS, React Fast Refresh, React.lazy code splitting and a production config.

React components are written in JSX, a syntax browsers do not understand. Webpack does not understand it either, so a React build needs a loader that turns JSX into plain JavaScript. The standard choice is babel-loader with @babel/preset-react. Around that core you add CSS handling, hot reloading with React Fast Refresh, lazy routes and a production profile.

This lesson walks through a complete, modern React setup and explains what each piece does. If you have not met loaders yet, they transform a file's source before it is added to the bundle; React itself is covered in its own track.

Webpack and React DOM are not run on this site, so the webpack and JSX snippets are read-only. The TryIt blocks are Node.js stand-ins that act out what the loaders do: a tiny JSX-to-function-call transform and a loader chain. They are simplified on purpose.

The packages

Terminal
npm install react react-dom
npm install -D webpack webpack-cli webpack-dev-server \
  babel-loader @babel/core @babel/preset-env @babel/preset-react \
  html-webpack-plugin css-loader style-loader \
  @pmmmwh/react-refresh-webpack-plugin react-refresh

@babel/preset-env compiles modern JavaScript for your target browsers; @babel/preset-react handles JSX. The two Fast Refresh packages give you state-preserving hot reloads.

The configuration

JavaScript
// webpack.config.js (read-only example)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ReactRefreshPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

const isDev = process.env.NODE_ENV !== 'production';

module.exports = {
  mode: isDev ? 'development' : 'production',
  entry: './src/index.jsx',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash:8].js',
    publicPath: '/',
    clean: true,
  },
  resolve: { extensions: ['.js', '.jsx'] },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', { modules: false }],
              ['@babel/preset-react', { runtime: 'automatic' }],
            ],
            plugins: [isDev && require.resolve('react-refresh/babel')].filter(Boolean),
          },
        },
      },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({ template: './public/index.html' }),
    isDev && new ReactRefreshPlugin(),
  ].filter(Boolean),
  devServer: { hot: true, historyApiFallback: true },
  devtool: isDev ? 'eval-cheap-module-source-map' : 'source-map',
  optimization: { splitChunks: { chunks: 'all' }, runtimeChunk: 'single' },
};

Key points:

  • runtime: 'automatic' uses the modern JSX transform, so you no longer write import React from 'react' in every file.
  • modules: false keeps ES modules intact so tree shaking works.
  • exclude: /node_modules/ keeps Babel from re-compiling dependencies, which saves a lot of time.
  • historyApiFallback makes the dev server return index.html for client-side routes.
  • Setting publicPath: '/' ensures lazy chunks load from the root even on nested routes.

What a JSX loader does

JSX is syntax sugar. <h1 className="title">Hi</h1> is converted into a call that builds an element description: jsx("h1", { className: "title", children: "Hi" }). This stand-in performs a much simpler version for plain tags with text, and then "renders" the result to a string, so you can see the pipeline (loader transform, then execution).

Node.js Stand-in: a toy JSX loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The real Babel plugin does this on a parsed syntax tree, handling nesting, fragments, expressions and spread props, but the idea is the same: the loader returns JavaScript that webpack can then follow like any other module.

Loaders run in a chain

When several loaders match a file, they run right to left (or bottom to top). ['style-loader', 'css-loader'] means css-loader runs first (turning @import and url() into modules), then style-loader injects the result into the page. Each loader receives the previous one's output.

Node.js Stand-in: right-to-left loader chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Fast Refresh

In development, ReactRefreshPlugin plus the react-refresh/babel plugin let you edit a component and see the change instantly while component state is preserved. Under the hood it uses webpack's HMR API (see the Dev Server and HMR chapter). Fast Refresh only works for function components with hooks, and it falls back to a full reload if you edit a file that exports non-components. Keep the refresh plugin out of production builds; it is guarded by isDev above.

Lazy routes with React.lazy

Combine React's lazy components with dynamic imports:

JSX
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';

const Dashboard = lazy(() => import(/* webpackChunkName: "dashboard" */ './pages/Dashboard'));
const Settings = lazy(() => import(/* webpackChunkName: "settings" */ './pages/Settings'));

export default function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Routes>
        <Route path="/" element={<Dashboard />} />
        <Route path="/settings" element={<Settings />} />
      </Routes>
    </Suspense>
  );
}

React.lazy requires the imported module to have a default export that is a component. Wrap lazy components in Suspense (and optionally an error boundary to catch chunk load failures). For routing details see React Router.

Production checklist

  • mode: 'production' with contenthash file names and runtimeChunk: 'single'.
  • process.env.NODE_ENV is production so React drops its dev warnings.
  • Extract CSS with MiniCssExtractPlugin instead of style-loader.
  • Set a browserslist so Babel does not over-transpile.
  • Check the size with the bundle analyzer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which preset makes Babel understand JSX?

    @babel/preset-react transforms JSX. preset-env handles modern JavaScript syntax for your browser targets.
  2. 2. In rules with use: ['style-loader', 'css-loader'], which runs first?

    Loaders are applied from last to first, so css-loader processes the file and style-loader injects its result.
  3. 3. Why set modules: false in preset-env?

    If Babel converts imports to CommonJS, webpack can no longer analyse unused exports.
  4. 4. What does React.lazy require from the imported module?

    lazy() expects a promise that resolves to a module whose default export is the component.
  5. 5. Where should ReactRefreshPlugin be used?

    Fast Refresh is a development convenience built on HMR. It should be excluded from production builds.

Summary

  • babel-loader with preset-env and preset-react compiles JSX; use the automatic runtime and modules: false.
  • Loader arrays execute right to left.
  • Fast Refresh gives instant, state-preserving updates in development only.
  • React.lazy plus import() splits routes into chunks.
  • Extract CSS, hash file names and analyze size for production.

Next: Webpack with Vue and Svelte