Exploring bundling in Lightning CSS

Exploring Bundling-Lightning CSS

With the rise of frameworks like Astro, which focuses on reducing a website’s load time, it’s clear that speed plays a crucial part in improving a website’s performance.

There are a variety of approaches you can take to increase your website’s loading speed, including removing excess JavaScript code, optimizing your images, performing lazy loading, and more. Alternately, you might consider minifying your website’s CSS.

In this article, we’ll learn how to bundle our CSS code using Lightning CSS, a CSS minifier. Let’s get started!

Jump ahead:

What is CSS minification?

CSS minification is the process of removing spaces, indentations, newlines, and comments from a CSS file, thereby reducing its size and converting it to a one-line code. With its lighter weight, the CSS loads faster, thereby reducing the website’s load time overall:

Initially, developers write CSS in beautiful, well-formatted code. But, before pushing the CSS code to production, they minify it for faster loading. Most modern frontend frameworks and libraries like React, Next.js, and Astro come with a CSS minifier pre-installed, and sometimes, you have the option to choose a different CSS minifier.

What is a CSS bundler?

We use a CSS bundler to handle dependencies during the minification process. Bundling is the process of creating an optimized bundle by resolving dependencies and merging the files.

While the CSS parser reads the CSS code and converts it into a structured format that can be understood by a web browser, the browser converts the bytes from the CSS into a data structure called CSSOM, which is equivalent to DOM for HTML. The diagram below represents the CSSOM structure:

CSSOM Process Flowchart Diagram

There are different CSS parsers for different programming languages; LESS is one for JavaScript.

What is a CSS transformer?

A CSS transformer is a tool or software that takes CSS code as an input and applies various modifications to it, for example, removing unnecessary whitespace, optimizing styles, or converting it into a different format or syntax. It can also include adding a prefix for different browsers that support different CSS properties.

The goal of a CSS transformer is to optimize and streamline the CSS code to improve performance and reduce the file size without changing how the styles are displayed in the browser.

What is Lightning CSS?

Previously called Parcel CSS, Lighting CSS is a CSS parser, transformer, bundler, and minifier written in Rust. In short, Lightning CSS runs on the CSS files to create an optimized CSS bundle for the web application.

In comparison to other JavaScript-based tools like esbuild and cssnano, minifying a large CSS file is much faster with Lightning CSS:

Time Minify Bootstrap Lightning CSS

Implementing Lightning CSS in different bundlers

Parcel

Parcel is an open source bundler. Built by the same person, Devon Govett, Parcel comes with built-in support for Lightning CSS. By default, Lightning CSS handles the CSS transformation; you can configure it in the package.json file from the root directory with the following settings:

  • drafts: Enables CSS nesting and custom media queries
  • psedoClasses: Handles pseudo classes like :focus-visible
  • cssModules: Enables CSS modules globally

Below is the code for the configurations above:

{
  "@parcel/transformer-css": {
    "cssModules": true,
    "drafts": {
      "nesting": true,
      "customMedia": true
    },
    "pseudoClasses": {
      "focusVisible": "focus-ring"
    }
  }
}

webpack

webpack is an another open source module bundler for JavaScript. We can integrate Lightning CSS with webpack using the css-minimizer-webpack-plugin, which comes with built-in support for Lightning CSS.

Using the command below, install lightingcss and css-minimizer-webpack-plugin. We’ve also added browserlist for targeting browsers:

npm install --save-dev lightningcss css-minimizer-webpack-plugin browserslist

Now, we can configure the webpack.config.js file. Import all the necessary modules from the library as follows:

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const lightningcss = require('lightningcss');
const browserslist = require('browserslist');

Below is the configuration:

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.lightningCssMinify,
        minimizerOptions: {
          targets: lightningcss.browserslistToTargets(browserslist('>= 0.25%'))
        },
      }),
    ],
  },
};

Vite

Let’s talk about the curious case of Vite. At the time of writing, there is no official way to integrate Lightning CSS with Vite because there are no plugins available for it. However, there is a third-party library; vite-plugin-lightningcss can only help you in transpilation, which is the process of converting modern CSS syntax code to support older browsers.

Install vite-plugin-lightningcss with the command below:

npm install --save-dev vite-plugin-lightningcss

Next, we just need to configure the vite.config.ts file using the code below:

import lightningcss from 'vite-plugin-lightningcss';

export default {
  plugins: [
    lightningcss({
      browserslist: '>= 0.25%',
    }),
  ],
};

Bundling in Node.js

Lightning CSS supports bundling for CSS code in Node.js applications. With the bundle function, we can minify and bundle the code from the specific file. bundle will return the code and map in buffer state; code is the minified code, and map is for the source maps of the file, which can be useful in debugging:

import { bundle } from 'lightningcss';

let { code, map } = bundle({
  filename: 'style.css',
  minify: true
});

Custom JavaScript resolver

To support custom resolvers, Lightning CSS supports the bundleAsync function, which is the asynchronous version of the regular bundle. It has support for adding a custom resolver, taking resolver as an object. The properties of the object are functions; read and resolve are the two functions, both of which are optional. Below is the code for the example:

import { bundleAsync } from 'lightningcss';

let { code, map } = await bundleAsync({
  filename: 'style.css',
  minify: true,
  resolver: {
    read(filePath) {
      return fs.readFileSync(filePath, 'utf8');
    },
    resolve(specifier, from) {
      return path.resolve(path.dirname(from), specifier);
    }
  }
});

Conclusion

In this tutorial, we explored minifying and bundling CSS using the Lightning CSS library, a tool that uses plugging to integrate with Parcel and other bundling applications. Some of them are not official plugins and have limited support. But, nonetheless, Lightning CSS is quite powerful when you use it as a library in Node.js.

If you want your favorite tool to integrate Lightning CSS, then you can pin them for plugins. Hopefully, this article helped you better understand bundling using Lightning CSS. Thanks for reading!

Is your frontend hogging your users’ CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — .




Source link