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

Optimizing CSS with CSS-Nano

Fixing Middleware Priorities in Express.js for Webpack Development

In this tutorial, you'll learn how to resolve middleware priority issues in Express.js that prevent your Webpack development server from reflecting real-time changes. By understanding and adjusting middleware priorities, you can ensure that hot refreshes function as intended.


Understanding Middleware Priorities in Express.js

Express.js processes middleware in the order they are defined. When a rule is placed first, it takes priority, often causing subsequent middleware to be bypassed. For instance, if files in the public folder are served first, Webpack's hot middleware won't have a chance to execute. This ordering issue disrupts the real-time update capability in a development environment.


Step-by-Step Fix

Step 1: Identify the Problem

The default middleware priority serves static files from the public directory before reaching Webpack middleware. This behavior must be overridden to ensure Webpack's dynamic updates are processed first.

Step 2: Adjust Middleware Order

  1. Modify the server setup to separate app creation from build setup:

    • Move the app initialization (app.use()) to a higher scope.
    • Ensure middleware like Webpack Dev Middleware is added before the static file middleware.

    Example:

    const app = express();
    
    // Add Webpack Dev Middleware first
    app.use(webpackDevMiddleware(compiler, {
        publicPath: config.output.publicPath
    }));
    
    // Add Webpack Hot Middleware
    app.use(webpackHotMiddleware(compiler));
    
    // Serve static files
    app.use(express.static('public'));
    

Step 3: Update Server Code for Flexibility

Split the server's app initialization and build methods:

  1. Introduce a getApp method to initialize the app early:
    const app = express();
    module.exports.getApp = () => app;
    
  2. Define a separate build method for server configuration:
    module.exports.build = (port) => {
        app.listen(port, () => console.log(`Server running on port ${port}`));
    };
    

This separation allows middleware to be dynamically injected before the app starts serving static files.


Validating the Changes

  1. Restart your development server.
  2. Test real-time updates by modifying your CSS or JavaScript.
  3. Verify that changes are applied dynamically without a full browser refresh.

What’s Next?

By fixing middleware priorities, you've ensured that your Webpack development server reflects changes in real time. Next, we'll dive into optimizing CSS with CSS-Nano, an essential step for a production-ready application. Stay tuned!


Ready to master React and Webpack? Access the full course here.

Using Next.js as an Optimal Alternative in 2024

In 2024, Next.js offers a highly streamlined and modern alternative to manually configuring Webpack and Express.js for server-side rendering (SSR), development hot-reloading, and production optimizations. Here’s why and how:


1. Built-in Webpack Configuration

  • No Manual Webpack Setup: Next.js abstracts the complexity of configuring Webpack for development and production. It automatically handles HMR, asset optimization, and build caching.
  • Extensible: If customizations are needed, Next.js provides a next.config.js file where you can override or extend Webpack settings without starting from scratch.

2. SSR and API Routes Out of the Box

  • Server-Side Rendering (SSR): Next.js includes SSR natively, making it an ideal choice for creating SEO-friendly, server-rendered React applications without extra middleware or custom configurations.
  • API Routes: Next.js supports serverless API routes, eliminating the need for a separate Express.js server in many cases.

Example:

// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js API' });
}

3. Optimized Development Experience

  • Fast Refresh: Next.js comes with a built-in Fast Refresh mechanism, which is more efficient than manually configuring HMR.
  • Integrated File-based Routing: File-based routing eliminates the need to configure and manage Express.js routes manually, enhancing developer productivity.

4. Production-Ready Optimizations

  • Static Generation with Incremental Static Regeneration (ISR): Next.js supports building pages at compile time or on-demand (when requested), offering flexibility between SSR and Static Site Generation (SSG).
  • Automatic Asset Optimization: Built-in CSS, JavaScript, and image optimizations with tools like PostCSS and SWC.

Why Choose Next.js Over Custom Builds in 2024?

  1. Speed and Simplicity: Out-of-the-box solutions for both development and production eliminate the need for manual Webpack configurations or middleware prioritization.
  2. Community and Ecosystem: Next.js has a vast plugin ecosystem and strong support from the open-source community, backed by Vercel.
  3. Future-proofing: Regular updates ensure compatibility with the latest React features and performance improvements.

Example Comparison

Custom Build Approach:

  • Requires managing Webpack, Express.js, middleware ordering, and plugins manually.
  • Great for educational purposes or unique project needs.

Next.js Approach:

  • Saves time with pre-configured best practices for modern applications.
  • Ideal for teams that prioritize fast delivery and maintainability over complete customization.

Conclusion

For most use cases in 2024, Next.js provides a superior alternative to custom SSR setups with Express.js and Webpack. While custom setups are still valuable for educational purposes or highly specific requirements, Next.js simplifies the process and ensures scalability, developer productivity, and production-grade performance.

Video Transcript

00:00It's time for us to focus on production specific stuff
00:03such as CSS.
00:04And right now our CSS is horrendous
00:06for a production environment.
00:08Part of the problem is that our code is just not minimized,
00:11but beyond that, we're doing a lot of wrong things
00:12that we're gonna see in this lecture.
00:14We're gonna use CSS Nano
00:16and optimize CSS assets, Webpac plugin
00:19to build up our CSS and get it to work.
00:22By the end of this session, our lecture really specifically,
00:25you're really gonna understand how to optimize your CSS
00:28and how to get it to work exactly the way
00:30you would want it to work.
00:33Alright, so now that we're getting the right files,
00:35our problem is very apparent
00:36that even though we have two bodies that are almost unique,
00:40we're not reusing them.
00:42And that's exactly what I want to do next.
00:44And to be able to do that, I'm gonna go ahead
00:46and install a few packages.
00:48Now, the first package that I'm gonna go ahead
00:50and install is called, is called, is called, is called
00:54Optimize CSS Assets web Pack plugin.
00:58I know it's a mouthful. NPM install.
01:01We're gonna need it only for the development environment
01:03or the packaging environment.
01:05And I'm gonna call for the optimized CSS assets
01:10web pack plugin.
01:12Now I need one more
01:13because this doesn't actually do, does the optimization.
01:16It's just the plugin that enables me
01:18to communicate with the optimizer.
01:20In this case, I'm gonna use the CSS nano,
01:22although it could accept other optimizers.
01:25Alright, so while this is installing, let's go ahead
01:28and add it into our web pack configuration.
01:30And I'm gonna choose to put it in our, um, joint venture
01:34for production and development
01:36because this is obviously needed for dev for production,
01:39but you might choose in development, maybe not
01:41to have it in there because you wanna speed
01:43up your packaging time.
01:45But personally I don't mind it.
01:46So I'm gonna go ahead and literally go ahead
01:49and by the way, if we're ready cleaning things up again,
01:52let's get rid of those extra constant definitions.
01:55Um, and I'm gonna go ahead
01:57and add one more, which is gonna be called Optimize
02:01CSS Assets plugin.
02:06Personally I would call this a better name.
02:09Really, it's too long for us.
02:10Okay, so require optimize CSS
02:16assets web pack plugin, that is a really,
02:21really long, long name.
02:23Okay, so app optimize CSS assets web pack plugin,
02:28that is our plugin.
02:29Once I've configured, once I've loaded up our plugin,
02:32I'm gonna go ahead in our plugins
02:34and just add a new plugin, which is gonna be that one,
02:36not surprisingly, and I'm gonna add some
02:38customizations to it.
02:40There's a few different customizations such as
02:42what files would you wanna compile down.
02:44In our case, we're it's automatically gonna take any CSS
02:47file, which is exactly what we need, which is our app css.
02:50But I do wanna configure
02:51and tell it that its CSS processor is gonna be
02:56require CSS nano.
02:58So I'm literally gonna send into it CSS nano.
03:01Secondly, I'm gonna go ahead to my CSS processor options
03:05and send into it a few options.
03:08So for one, for example, let's go ahead
03:10and just send nothing in the beginning
03:12and let's run it without putting anything.
03:14And let's see how the default is going to work.
03:17Now, if I go ahead here
03:19and into my app here, make sure
03:20that everything is done loading it is,
03:23and I will go ahead and start our server.
03:26Now as we're starting up our server,
03:27what is actually gonna happen is gonna also optimize our CSS
03:31and you can see that it dropped our CSS by 80%
03:34and by default, if I go ahead here
03:36and click here on refresh, we're gonna see
03:38that it's gonna compile down our code,
03:40it's gonna take our background setting
03:42and set it to be the color that we want it to be and
03:45and so on and so forth.
03:46So, but for example, there's a lot of different properties
03:49that you could play with, but the defaults are quite good.
03:51But if, for example, you wanted to not keep your comments,
03:55for example, so you could have set your discard comments
03:59to be false.
04:00So I could go ahead here and if I could just,
04:02if I go into my code here, I could set one of my properties
04:05as discard, discard comments
04:09and I could set that What, what, what should I just do?
04:11Discard comments. False.
04:13So we'll not discard comments, but I'm gonna have to restart
04:16because this is part of our configurations.
04:18So if I go ahead here, let me just break
04:20out, start over again.
04:22And if I do that this time around,
04:23we should still keep our CSS
04:26and you can see that now our files are a lot bigger.
04:28We only saved 50%, roughly 50%.
04:31And in this case we'll see
04:32that we're gonna still have all the comments even
04:34though it compressed it down.
04:36So there's a lot of different configurations that you could
04:38reenter or into the application,
04:40although obviously, um, the default of cs,
04:44the default CSS processor just works
04:46perfectly the way it is.
04:47You know, let me just leave that there in case you wanna
04:49play around with it and put in different configurations.
04:52But generally speaking, this is what we wanna do
04:54to get our production ready.
04:56CSS. Now the CSS will automatically transcribe down a lot
05:00of things and if you could take a look into the document
05:03provided, you'll find more things you could configure
05:04and customize based on your specific needs, such
05:07as getting rid of extra, um, browser specific, uh, CSS
05:12that is not needed or getting rid
05:14of printed information If you have like a print option
05:17but you don't want it on a specific page.
05:19So you could literally very fine tune,
05:21remove out features from CSS and also clean things out.
05:24Um, and that's it. That's CSS nano in a nutshell.
05:27And it's a very, very powerful feature
05:30to enable you to code spec.
05:32Specifically if we go back into our application
05:34and now go to our client
05:35and this time around we're gonna comment out
05:38that importation
05:39and instead of that import our full build, it'll see
05:42that even though in our bootstrap we're actually,
05:45every time we load a button,
05:46we're also loading a few different things
05:48and there's a duplication in this load process
05:51that basically creates a lot of extra CSS
05:54that is the exact same thing that is just not needed.
05:56But because we've added this in, now,
05:58if we take a gander at our CSS, once it's compiled down,
06:02it's gonna remove a lot of those extras.
06:04So to make it really vivid, lemme just go ahead here
06:07and in our code here, I'm just gonna go into our pack here
06:11and just for the, for just for a second, you know,
06:13let just create here another, let's lemme call it just pack
06:16and I'm just gonna call web pack, okay?
06:20And let me just go ahead
06:21and stop our server here for a second
06:24and I'm gonna call NPM Run Pack.
06:26Now, when I run my pack, you're gonna see
06:28how small our code will become, even
06:30with relatively speaking, this is quite small.
06:33Uh, but sp specifically, if we take a look at it,
06:37once it's done with the optimization,
06:39we should see our CSS file
06:41and we'll get a sense the size of this,
06:43uh, of this final file.
06:44And you see that our CSS is 50 k.
06:47Now, if I get rid of the optimization,
06:49so if I just go ahead here in my, uh, configure here
06:53and I'm just gonna go ahead and remove this whole new plugin
06:57and not optimize it
06:58and give it another shot, we'll see
07:00that from 50.3 K we're gonna explode up
07:04to a much bigger file because of all these duplications.
07:07So literally just by putting one line
07:09of code in there over this line of code that we've created,
07:11we literally drop the file of our actual real build CSS
07:15by 75% or more than 75%.
07:18Actually, uh, I think that's 80%, which is, uh, amazing.
07:20Okay? So make sure that you do put that in any product
07:23and per, personally, I put
07:25that into my production end development.
07:27'cause then if there's any mistakes in the optimization
07:30or if I think that something should be first or second
07:32or I don't know what, while it's being compiled down,
07:35then it's more easy for me to notice
07:36that those stuff actually aren't working
07:39as I should, as they should.
07:41So it makes it easier for me how it, to see
07:43how it actually looks like on a real browser
07:44by optimizing it all the time.
07:47In this lecture, we optimize our CSS
07:50and in the next one we're gonna move into optimizing our
07:52JavaScripts and getting it ready for production.

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!