Skip to content

Sample Configuration

Below is a comprehensive sample configuration, which does the following:

Install Dependencies

# Webpack dependencies
pnpm i -D webpack webpack-dev-server webpack-cli @swc/core swc-loader styled-loader css-loader html-webpack-plugin @pmmmwh/react-refresh-webpack-plugin react-refresh

# React
pnpm i react react-dom
pnpm i -D @types/react @types/react-dom

# Typescript
pnpm i -D typescript @tsconfig/recommended

tsconfig.json

See Typescript for more details.

tsconfig.json
{
    "extends": "@tsconfig/recommended/tsconfig.json",
    "compilerOptions": {
        "jsx": "react-jsx"
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules"]
}

Webpack Config

webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");

const isDevelopment = process.env.NODE_ENV !== "production";

/** @type {import("webpack").Configuration} */
module.exports = {
    mode: isDevelopment ? "development" : "production",
    entry: "./src/main.tsx",
    resolve: {
        extensions: [".ts", ".js", ".tsx", ".jsx"],
    },
    output: {
        publicPath: "/",
        clean: true,
    },
    devServer: {
        // Enable hot reloading
        hot: true,
        port: 3000,
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "swc-loader",
                        options: {
                            jsc: {
                                transform: {
                                    react: {
                                        // swc-loader will check whether webpack mode is 'development'
                                        // and set this automatically starting from 0.1.13. You could also set it yourself.
                                        // swc won't enable fast refresh when development is false
                                        refresh: isDevelopment,
                                        // Enable the new JSX runtime module (e.g. `react/jsx-runtime`)
                                        runtime: "automatic",
                                    },
                                },
                            },
                        },
                    },
                ],
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: "My app",
        }),
        isDevelopment && new ReactRefreshWebpackPlugin(),
    ].filter(Boolean),
};

src/main.tsx

src/main.tsx
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.createElement("div");
document.body.appendChild(rootElement);

const root = createRoot(rootElement);
root.render(<App />);

Last update: August 12, 2023
Created: June 3, 2023