02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Fixing our priorities

Setting Up Hot Refresh Middleware for Webpack

In modern web development, hot refresh middleware plays a crucial role in streamlining your development workflow. By enabling real-time updates, it allows changes to be reflected instantly without refreshing the browser. This tutorial walks you through the essential steps to configure hot refresh middleware in your Webpack-powered development environment.


Why Hot Refresh Middleware?

Using hot module replacement (HMR) enhances productivity by:

  1. Instantly updating UI changes.
  2. Preserving application state during updates.
  3. Reducing build and reload times.

Step-by-Step Guide

Step 1: Install Required Packages

To begin, you’ll need to install two middleware packages:

npm install --save-dev webpack-dev-middleware webpack-hot-middleware
  • webpack-dev-middleware: Integrates Webpack’s development server with your Express app.
  • webpack-hot-middleware: Enables HMR functionality for real-time updates.

Step 2: Update Your Webpack Configuration

Modify your Webpack configuration to include HMR support:

  1. Add the following to your entry point:
    entry: [
        'webpack-hot-middleware/client',
        './src/index.js'
    ]
    
  2. Add the HotModuleReplacementPlugin:
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ]
    

Step 3: Configure Express Middleware

Integrate Webpack into your Express server:

  1. Require the necessary modules:
    const webpack = require('webpack');
    const middleware = require('webpack-dev-middleware');
    const hotMiddleware = require('webpack-hot-middleware');
    const config = require('./webpack.config.js');
    const compiler = webpack(config);
    
  2. Add the middleware to your Express app:
    app.use(middleware(compiler, {
        publicPath: config.output.publicPath
    }));
    app.use(hotMiddleware(compiler));
    

Step 4: Enable HMR in the Client Code

In your main JavaScript file, add:

if (module.hot) {
    module.hot.accept();
}

This ensures that HMR listens for changes in the client code and updates the browser dynamically.


Tips for Success

  • Separate Configurations: Consider maintaining distinct configuration files for development and production environments.
  • Check Dependencies: Ensure you’re using compatible versions of Webpack and the middleware packages.

What’s Next?

With your hot refresh middleware configured, you’ve laid the groundwork for a highly efficient development environment. In the next tutorial, we’ll explore integrating Webpack Dev Middleware with a real server for a seamless development-to-production transition.


Ready to dive deeper into React performance optimization? Explore the full course now!

Analysis of the Approach and Updates for 2024

The video outlines how to manually set up Webpack Dev Middleware and Hot Middleware to bridge the gap between development and production environments. While this approach was valuable in earlier years, more efficient methods exist in 2024.


Preferred Approach for Development Middleware in 2024

  1. Use Modern Dev Servers:

    • Vite and Next.js provide built-in solutions for development environments without requiring manual middleware configuration. They handle:
      • File serving.
      • Hot Module Replacement (HMR).
      • Optimized builds.

    Example: Setting up Vite for React:

    npm create vite@latest my-react-app --template react
    cd my-react-app
    npm install
    npm run dev
    
  2. Webpack's Built-In Features:

    • Webpack 5 supports webpack-dev-server natively, eliminating the need for additional middleware.
    • The configuration becomes simpler and leverages features like automatic HMR, file serving, and improved logging.

    Example Configuration:

    const path = require('path');
    
    module.exports = {
        mode: 'development',
        entry: './src/index.js',
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, 'dist'),
        },
        devServer: {
            static: path.join(__dirname, 'dist'),
            port: 3010,
            hot: true, // Enable HMR
            open: true, // Auto-open browser
        },
    };
    
  3. Separate Configurations for Development and Production:

    • Instead of injecting entries and modifying configurations dynamically, maintain two distinct config files:
      • webpack.config.dev.js: Focused on features like HMR, sourcemaps, and lightweight builds.
      • webpack.config.prod.js: Optimized for production with minification, caching, and tree-shaking.

    Example:

    // webpack.config.dev.js
    const path = require('path');
    
    module.exports = {
        mode: 'development',
        entry: [
            'webpack-hot-middleware/client',
            './src/index.js',
        ],
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, 'dist'),
        },
        devtool: 'inline-source-map',
        plugins: [
            new webpack.HotModuleReplacementPlugin(),
        ],
    };
    
  4. Streamlined Middleware: If sticking with Express and custom middleware, libraries like webpack-dev-middleware are still valid. However, with Webpack 5, it's better to integrate webpack-dev-server for an all-in-one solution.

    Example Middleware Integration:

    const webpack = require('webpack');
    const middleware = require('webpack-dev-middleware');
    const hotMiddleware = require('webpack-hot-middleware');
    const express = require('express');
    const config = require('./webpack.config.dev.js');
    
    const app = express();
    const compiler = webpack(config);
    
    app.use(middleware(compiler, {
        publicPath: config.output.publicPath,
    }));
    
    app.use(hotMiddleware(compiler));
    
    app.listen(3010, () => console.log('Dev server running on http://localhost:3010'));
    

Why Modern Tools Are Preferred in 2024

  1. Simplicity:

    • Tools like Vite and Next.js reduce setup complexity, allowing developers to focus on building features rather than configuring environments.
  2. Performance:

    • Modern dev servers provide faster builds and reloads due to optimized build pipelines and support for ES Modules.
  3. Improved Debugging:

    • Features like enhanced error overlays, better logging, and state-preserving HMR are built-in.
  4. Future-Proofing:

    • Aligning with tools actively maintained and designed for modern ecosystems ensures compatibility with the latest standards.

Conclusion

While the method described in the video remains valid, it is no longer the optimal approach in 2024. Leveraging modern tools like Vite, Next.js, or webpack-dev-server simplifies the process, enhances developer experience, and ensures efficient builds and runtime performance.

Video Transcript

00:00While we're very close to our running application
00:02or a development environment, we have a problem.
00:05Even though our code is re rendered the way it should be,
00:08we can't see those changes.
00:10And namely the problem we have here is
00:12priorities in express.
00:14Express works this way.
00:16Whatever rule you put first,
00:17which is the word when we use the dot use, that is the uh,
00:20rule definition we've put in.
00:22Anytime we add a rule, it has a first priority.
00:25So later priorities that we use
00:27with our middlewares are just not applicable
00:29because the files exist already in our public folder.
00:32So we're gonna learn in this lecture how
00:34to change those priorities
00:35so our dev dev server will actually work again
00:38with hot refreshes.
00:40Alright, while you were away, I went ahead
00:43and made a couple of changes
00:45and I wanna walk through them with you.
00:46One is I've added the test CSS file,
00:49which is basically just this body and background
00:52and I duplicated it and made a small change to it.
00:55So if in the first it had one background which was the same,
00:59I've added Otto a red color for its color.
01:02Okay? Now the next thing
01:03that I'm gonna do is I'm gonna go into my client
01:05and I want to comment everything out here.
01:08And instead of that, all I'm gonna do is I'm just gonna
01:10import those two CSS files
01:12for the sake of this presentation.
01:14So I'm just gonna go ahead and ask for tests css,
01:17and I'm gonna import OTO test two css.
01:22Okay? So let's go ahead and save this.
01:24And I'm first of all gonna show you a problem
01:25that we have currently in our current build structure
01:28that we need to sort out and fix.
01:29And part of it is because we're working
01:31with one config file, but it's a really good practice
01:34'cause now you're gonna understand really well how to work
01:37with Webpac, which is critical
01:38for building up optimized production applications.
01:42Okay, so with that said,
01:43what I wanna do is I wanna run my server.
01:45So I'm gonna go into my package
01:47and I want to just make sure that I re in
01:50while you weren't here.
01:52I started whenever we're starting our dev environment,
01:56then we're good, we're good.
01:57We're just starting the server.
01:58And then it should start recompiling the code.
02:01Whenever we're doing the production,
02:02then we are separately web packing
02:05and then we're doing the server production.
02:07So, but we are gonna have a problem here.
02:10So what will happen though? What's gonna happen though?
02:13Even, even though web is gonna compile down our code
02:16and get it ready, if we actually go
02:19and try to see it, if we're gonna try
02:20to see our code right now, that should be just a really
02:22simple small amount of CSS.
02:24Let me just go to the right IP oso.
02:26Um, we'll see that our files are gonna still serve
02:29up the old files.
02:30Now the reason is very simple.
02:32The reason is, is because when we're compiling down our code
02:34work, originally when we compiled down our production code,
02:38which happened in our node server prod
02:41or Webpack more accurately, we compiled down our code
02:44and placed it into the public folder.
02:47After we've done that, our server itself automatically,
02:50because this line right here says, I'm going
02:53to use first whatever is inside
02:54of the public folder only if I cannot
02:57find something in the public
02:58Folder, then I'll do whatever is in this line
03:01and then this line and then whatever
03:02line that follows through.
03:04Now because in our server development environment,
03:06when we call the app, the public area is already configured.
03:10We basically, whatever we're putting here is happening
03:13defacto, which basically means they're not going to happen,
03:15they're not gonna be visible to the user
03:17because we already have a public file that is accessible,
03:21but fear not because we could solve this very easily.
03:23What we wanna do is we wanna separate the steps
03:26of the creation of the app from the actual build itself.
03:29So I'm gonna take that require
03:31and get ourselves our server once we have our server up.
03:35And I'm gonna go ahead here.
03:36What I want to do is I want
03:37to ask from my server to fetch us.
03:39And by the way, the server build, we're,
03:41we're gonna do in a minute,
03:42but let's place it right here in the bottom in the end.
03:45But we also want to ask our server, for example, to get app.
03:48So we're gonna get the application
03:49before we actually build up the complete server.
03:52Now to do that, we're gonna have to also change
03:54our server a little bit.
03:56For one, we're gonna need to use this app on a global scope.
03:59So I'm gonna push that up and if we're already here,
04:01let's clean up and make this code a little bit more highly
04:04optimized because we just need one cons.
04:06We don't need more than one.
04:08And let me just do the last one as well.
04:10And fear not because this is not the global scope,
04:12this is the module scope.
04:14So it's gonna only live within this module, which is good.
04:17Beyond that, we also want to split that build
04:20and add one more method before the build
04:22and let's call it that get app
04:23that we've just uh, mentioned.
04:25And it doesn't ask for, it doesn't need any parameters,
04:28but it is going to return to us the app
04:31that has been created already.
04:32So we're gonna return the app. Oh, just return app.
04:35It's not a method. Okay?
04:37So now that we've done this step,
04:38let just walk through it again.
04:40Now that we split the app creation
04:42and had to have done it in advance from the build itself,
04:45what we actually did is enabled us to inject our code
04:49before the default operations, which is exactly
04:51what we need, where we're gonna be working
04:53with Webpac in our case scenario.
04:55So if I go ahead and test this out one more time
04:57and I'm gonna break out my build
04:59and start our product again, when it's gonna compile down
05:03and have our webpac done
05:05and ready, which is gonna take it a few seconds
05:07'cause it's compiling it down.
05:09Once that compiled process is, is done and the CSS is ready
05:12and the JavaScript is ready,
05:14if I go back into my application
05:16and click around refresh,
05:17I should be getting, oh, let me double check.
05:22Oh, I forgot to save. Oh my bad. Ignored this part.
05:25I undid that while I was playing around
05:27and let's see if it's gonna compile, it compiled down.
05:30And if I click here on refresh now,
05:32we should now see the files as they were intended
05:35to be in this lecture.
05:39We learned about the priorities and express js
05:41and through that made our dev server to work.
05:44And now that we're done with configuring
05:46and setting up our production
05:48and development, well our development server, it's time
05:50for us to move into production specific things, starting
05:52with optimizing our CSS with CSS nano,
05:56which we'll do in the next lecture.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!