ยท react

Setup Webpack HMR with NestJS and React

This article explains how to set up a NestJS server with Webpack's Hot Module Replacement (HMR) to host a React web application. It provides code examples and instructions on how to access the Express instance from the NestJS framework and how to bring Webpack and its HMR plugin to your React web application.

Programmatically setup a Nest.JS server with Webpack's Hot Module Replacement (HMR) to host a React web application.

Contents

Setup

Setting up a NestJS server with Webpack's Hot Module Replacement is as simple as setting up an Express server with Webpack's HMR. The key is to get access to the Express instance from the NestJS framework:

server/RootModule.ts
import { Module } from '@nestjs/common';
 
@Module({
  imports: [],
})
export class RootModule {}
server.ts
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { RootModule } from './server/RootModule';
import type express from 'express';
 
const nestApp = await NestFactory.create<NestExpressApplication>(RootModule);
const httpAdapter = nestApp.getHttpAdapter();
const app: express.Express = httpAdapter.getInstance(); // Instance of your "Express" server

Here is a generic function to bring Webpack and its HMR plugin to your React web application served by an Express server:

initWebpack.ts
import express from 'express';
import { HotModuleReplacementPlugin, webpack } from 'webpack';
 
function initWebpack(app: express.Express) {
  const webpackCompiler = webpack({
    entry: ['webpack-hot-middleware/client', `${__dirname}/webapp/App.tsx`],
    mode: 'development',
    module: {
      rules: [
        {
          exclude: /node_modules/,
          test: /.[tj]sx?$/,
          use: {
            loader: 'babel-loader',
            options: {
              plugins: ['@babel/plugin-proposal-class-properties'],
              presets: ['@babel/preset-react', '@babel/preset-typescript'],
            },
          },
        },
      ],
    },
    plugins: [new HotModuleReplacementPlugin()],
    resolve: {
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
  });
 
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
 
  app.use(webpackDevMiddleware(webpackCompiler));
  app.use(webpackHotMiddleware(webpackCompiler));
 
  app.use(express.static(`${__dirname}/webapp`));
}

Tested with

  • @nestjs/common 7.6.3
  • @nestjs/core 7.6.3
  • @nestjs/platform-express 7.6.3
Back to Blog