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

Getting Webpack JavaScript to Be Production Ready

How to Optimize CSS for Production with CSS-Nano and Webpack

Introduction

Optimizing CSS for production environments is critical to ensuring fast load times and a seamless user experience. In this tutorial, you'll learn how to use CSS-Nano and the Optimize CSS Assets Webpack Plugin to minify, deduplicate, and streamline your stylesheets. By the end of this guide, your CSS files will be cleaner, smaller, and ready for deployment.


Step 1: Install Required Packages

To begin, install the necessary dependencies:

npm install optimize-css-assets-webpack-plugin cssnano --save-dev
  • Optimize CSS Assets Webpack Plugin: Integrates with Webpack to optimize CSS.
  • CSS-Nano: Performs the actual optimization of CSS files.

Step 2: Configure Webpack

Update your Webpack configuration to include the optimization plugin:

  1. Import the plugin:

    const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
    const CssNano = require('cssnano');
    
  2. Add the plugin to your plugins array:

    plugins: [
      new OptimizeCSSAssetsPlugin({
        cssProcessor: CssNano,
        cssProcessorOptions: {
          discardComments: { removeAll: true }, // Removes all comments
        },
      }),
    ];
    
  3. Optional: For development, decide whether to include the plugin for faster builds.


Step 3: Run and Test the Optimization

  1. Start your build process:

    npm run build
    
  2. Observe the difference in CSS file sizes before and after optimization.

    • Original CSS file: ~200 KB
    • Optimized CSS file: ~50 KB
  3. Ensure functionality remains intact by testing the application in a browser.


Step 4: Additional Configuration Options

CSS-Nano offers various configurations for specific needs:

  • Remove unnecessary browser-specific prefixes:
    autoprefixer: false,
    
  • Control minification levels: Adjust settings to suit your application's requirements.

Refer to the CSS-Nano documentation for advanced usage.


Conclusion

By integrating CSS-Nano and Webpack, you can significantly enhance the performance of your web applications. Optimized CSS not only reduces file sizes but also ensures faster rendering times, leading to better user experiences. In the next tutorial, we'll move on to optimizing JavaScript for production readiness.

2024

In 2024, optimizing CSS and other assets for a React-based project can be streamlined by leveraging modern tools and frameworks that abstract away much of the manual configuration. Here's the optimal approach for a new React-based project:


1. Use a Modern Framework like Next.js or Remix

Frameworks like Next.js and Remix come with built-in optimizations for production-ready applications, including CSS and JavaScript minification, image optimization, and server-side rendering (SSR). They reduce the need for manual setup and provide an opinionated structure to accelerate development.

Benefits:

  • Built-in CSS Support: Next.js supports CSS modules and can import CSS directly in components.
  • Automatic Code Splitting: Only the code needed for the current page is loaded.
  • Built-in Minification: Next.js uses SWC (or optionally Webpack) to minify both JavaScript and CSS.

Setup:

  1. Install Next.js:
    npx create-next-app@latest my-app
    cd my-app
    npm run dev
    
  2. Import CSS files or use CSS-in-JS libraries like styled-components or Tailwind CSS for styling.

2. Leverage Tailwind CSS

In 2024, Tailwind CSS remains a top choice for managing styles efficiently in React projects. Tailwind's utility-first approach, combined with features like tree-shaking and automatic purging of unused CSS, ensures minimal CSS size in production.

Steps to Integrate:

  1. Install Tailwind:
    npm install -D tailwindcss postcss autoprefixer
    npx tailwindcss init
    
  2. Configure Tailwind to remove unused styles:
    In tailwind.config.js:
    module.exports = {
      content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
      theme: {
        extend: {},
      },
      plugins: [],
    };
    
  3. Import Tailwind in your global styles:
    import './styles/globals.css';
    

3. CSS Optimization Tools

If not using a framework like Next.js, modern build tools like Vite or CRA (Create React App) offer built-in optimization or plugins for CSS.

  • Use PostCSS and plugins like cssnano for minification.
  • Integrate tools like PurgeCSS to remove unused styles.

4. CSS-in-JS Alternatives

For dynamic styling, consider CSS-in-JS libraries such as:

  • Emotion
  • Styled-Components

These libraries optimize styling by injecting critical CSS and avoiding unused styles, ensuring high performance.


5. Static Site Generation (SSG) and Server-Side Rendering (SSR)

React frameworks now favor a hybrid approach where some pages are statically generated, while others are server-rendered based on the use case. Next.js, for example, allows:

  • SSG for high-performance pages served statically.
  • SSR for dynamic pages needing real-time data.

6. Use Modern Bundlers

Tools like Vite or esbuild are faster and more efficient than Webpack for new React projects. These tools are designed for modern JavaScript applications, offering quicker builds and smaller output sizes.

Why Choose Vite:

  • Lightning-fast development server.
  • Built-in CSS and asset optimization.

7. Best Practices for Production

  • Code Splitting: Ensure unused code is not included in the bundle. Use React.lazy and Suspense for dynamic imports.
  • Image Optimization: Use tools like next/image (Next.js) or services like Cloudinary for automatic optimization.
  • Environment Variables: Keep your environments clean with .env files for production-specific configurations.
  • Monitoring and Profiling: Use tools like Lighthouse, Sentry, and React DevTools to identify bottlenecks.

Conclusion

For a new React project in 2024, the preferred approach balances productivity and performance by leveraging modern frameworks like Next.js, CSS tools like Tailwind, and optimized build tools like Vite. These tools not only simplify development but also ensure best-in-class performance out of the box.

Video Transcript

00:01Now that we have our CSS optimize, it's time for us
00:03to optimize our JavaScript for production as well.
00:06We're gonna remove a develop code that is not relevant
00:09for development and we're gonna also optimize the
00:12code and minify it.
00:13So let's jump right into it and let's see it in action.
00:16Alright, so before I started recording,
00:18I ran the command NPM Run pack.
00:20So we could take a look at our index js
00:23that currently is 934 kilobytes.
00:26Now there specifically
00:28and deliberately there are different builds
00:31for production and for development.
00:33While in development there's a lot of debugging
00:35and unit testing and other features
00:38that are integrated into our application to make sure
00:41that we could do different things.
00:43But once we are done with that, we really want to get rid
00:46of it in our production environment settings.
00:48Now, moreover that even
00:50before we take a look at that, I wanna also just note
00:52that you could decide what is gonna be the development mode,
00:56which basically makes sure
00:58that it's org gonna be more highly efficient,
01:00more highly optimized,
01:02or it's going to use a cheaper amount of time
01:05and create the resources faster,
01:07which would end up creating the files larger.
01:10Now, generally speaking,
01:11when you would create those two separate files, one
01:13for the production, one for the development,
01:16you would have oso in your config.
01:17And I'm just gonna add it just here. config.dev tool.
01:23And you would define what tool that is.
01:25For example, inside of your development environment.
01:27A good one would be a vial.
01:28What a V would do is, is create a development packaging.
01:32Know, lemme put it Otto inside of our web pack here inside
01:35of our configuration for web pack as well for a minute, just
01:38as, um, until we actually create the right
01:42var variable that we want there.
01:43So I'm just gonna put your eval.
01:45Now what eval is gonna do is it's gonna go through, uh,
01:48dev tool and let me just run it Oto.
01:51So let me just, uh, so before we were 930 4K,
01:54and if I run it again, it's going to grow a little bit
01:57because it's not gonna be as highly optimized.
01:59It's going to take a little bit less time
02:02to build that full package.
02:03But moreover than that, once it's completed building
02:06that package, it's also gonna package up a mapping
02:08of the information, which that mapping will basically, uh,
02:15not be in existence, but our file will grow exponentially.
02:20So you can see not exponentially if we were at 934,
02:23now we're gonna be at 979
02:26and if we take a peek into our directory, we'll see
02:28that our files are there and they are much larger.
02:32Now let's go ahead and take a deeper look at, at,
02:35at a good configuration.
02:37And this good configuration,
02:38I'm just gonna go ahead and type it here.
02:40This is gonna be our production version
02:42and it's called cheap module source map,
02:47which basically creates also a,
02:49you could say like an intermediary map
02:51that speeds up the build itself,
02:54but it also makes sure that our production could build up
02:57and be more efficient,
02:58or technically speaking, it's really gonna do what we saw
03:01with doing in default before it played with things around,
03:04but then it's stored into it, it's stored into,
03:07supposedly into the virtual cloud.
03:09It didn't store it into a physical file file,
03:11which is completely fine for our needs really,
03:14but this is another opportunity, another option for you
03:16to distinguish between your production versus your vial.
03:20So if you want to have that a vial
03:21that is maybe more efficient
03:23because it's, it's, it's, it's, it's compiles itself faster.
03:27Technically speaking, I probably would just use the cheap
03:29module source map generally,
03:31and that's gonna give you, uh, a, a a a footprint
03:34that is larger, which would, which enable Webpack
03:37to package things much faster as it's condensing it down to
03:40that 934.
03:41So if we rerun it again, for example,
03:43and it runs it, it's gonna,
03:45it's gonna take it a little bit less time to run
03:47through the code to check and see um, are there any changes?
03:51It's gonna be able to go through
03:52that process just a little bit faster
03:54because it has tho those maps as well.
03:56Nothing really major for us in our, in our scenario.
04:01Okay, so with that said, let's continue down
04:03to making our code really where the optimization happens
04:07and uh, to, for, for us to be doing that.
04:09I'm gonna go ahead and do it inside
04:11of our regular web echo though this is used
04:14by our production and our development,
04:15which in a real world scenario, you probably would want
04:18to separate this out into two separate files.
04:20And I'm gonna go ahead and ask to define another plugin,
04:24which I could use probably the same uh,
04:26definition that we're putting here.
04:27Uh, I could reuse it,
04:29but just for the sake of keeping things separate,
04:31I'm gonna create another web pack plugin
04:33and this web pack plugin is gonna have a process.
04:37And by the way, this, this, uh, variable process
04:40environment is expected by a lot of different applications
04:45and in it we could basically say our node and environment
04:48and literally defined if our environment is gonna be, uh,
04:52production and which is basically what I'm gonna do here,
04:54string afi and I'm gonna set it to be production.
04:58Lemme just also break a few lines.
05:00So basically what I've done here is I basically created a
05:04variable that will be available to web pack
05:06and whatever is there, which is basically process
05:09that n node environment.
05:11Um, and what that would do is any place where there's an if
05:14around surrounding that, which is basically
05:17what is actually gonna happen is inside of React.
05:19There's a lot of places and a lot of other applications
05:22as well where you have Process pro.
05:25Yeah, that's not what, that's not process.
05:28So you have the, you have basically process environment
05:33note dot node environment.
05:37And it's gonna ask here, does this equal
05:40production or more accurately?
05:42Does it exactly not equal production?
05:44And only if it's not production,
05:46then it's gonna do all the different debuggings and errors
05:48and all these different wonderful things
05:50and all these stuff happened behind the hood.
05:52Now what we're doing here is we're basically telling Webpac
05:54that while you're packaging this up, also know
05:57that we're in the production environment now by doing this
06:01and by setting it and configuring and adding this code up.
06:04And let me just so we save a little bit
06:06of time becauses so many different words here.
06:08Let me just make sure that I don't have here any typing
06:10hours and let me go ahead and save this
06:12and run it one more time.
06:14Once now we're gonna run it if we were at 9 34 a moment ago,
06:17now that it's gonna get rid
06:19of all these non-production related code,
06:22it's gonna strip that out as well.
06:23And when it's gonna strip it out as well,
06:25it's gonna reduce our file even more.
06:27So, so now we're gonna be in the 800 and something,
06:29'cause it already did it in advance, so I know it's gonna be
06:31882.
06:33So we can see our file size has been dropped already
06:35by almost a hundred k.
06:37If we started off by 9 9 79, now we're at, uh, 8 82.
06:42But let's continue. Now, beyond that,
06:43we also wanna amplify our code.
06:45So I'm gonna go also and add another plugin
06:47and I'm gonna call the new web
06:49pack Optimize.
06:54And by the way, there's a lot of other optimization things
06:56that you could do, which you're more than encouraged
06:58to check out, which would even more highly improve
07:01your optimization.
07:02I'm gonna go into Phi Js plugin
07:07and I'm just gonna go ahead and run it.
07:09And if I run it, well basically instantiate it.
07:13And if I run my code just one more time now it's gonna oto
07:15package it up and oto compress it
07:18and oh, I have your little error.
07:19Um, what is the error? It is probably in that line.
07:22Let's see if what we have your web pack optimize, amplify
07:27js is and lowercase J here.
07:31Okay, so let's give it another shot And what it should do,
07:35it should really package it up.
07:36And this time around when we're amplifying our code
07:38and really trying to condense it as much as we can,
07:41we're gonna get a dramatically smaller file size.
07:43Uh, literally I think we we're gonna gonna get down to
07:46around two hundred and thirty, two hundred and twenty three
07:49kilobytes, which is gonna cut down our size of our site
07:52by our JavaScript by almost 75%, which is awesome,
07:55which is brilliant, which is exactly what we need.
07:59And that's it. That's basically what you're gonna do
08:01with in your optimizations.
08:02Now, by the way, you could see here all these different, um,
08:05messages that it's telling you about what it's doing
08:09and things that it's just telling you, Hey,
08:10by the way, this is a constant.
08:12And all these stuff usually is not relevant, uh, to us
08:15because it's inside of the libraries that we're using.
08:17So if it annoys you
08:19and you actually want to see the actual outcome without
08:22actually seeing all these errors, then you could go ahead
08:24and just, uh, not errors,
08:25but uh, notices, you could go inside
08:27and in your compress you could give it basically a command
08:31saying warnings, We don't wanna
08:36get our Wawa warnings.
08:41And if I go ahead and just run this just one more time
08:44and with it complete our our build, uh, we'll see
08:48that we're not gonna get those errors anymore.
08:49Once it's compressed, it's just gonna give us the file
08:51sizes, just the way that we would want
08:53to get it in this type of scenario.
08:56Um, and that gives it, that's it.
08:57That's really, we, we just, uh,
08:59compressed down our CSS in the last lecture.
09:02We've now just compressed our JavaScript
09:04and we're really production ready.
09:05Our code is now complete, you could say.
09:08And if we let it finish up, we'll be able to OOC
09:12that our JavaScript now is 223
09:16kilobytes in this lecture.
09:18We prepared our code and now our JavaScript
09:20and our CSS is ready and we're really almost done.
09:23The last thing that's left for us to do is
09:24to focus on the server itself for a minute,
09:26where in the next lecture we'll cache
09:28and compress our assets, making sure
09:30that we're gonna render our items in the most optimal way
09:33for browsers.

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!