iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📑

Integrating Lightning CSS into Vite

に公開
2023/07/31

I recently learned about Lightning CSS, so I would like to introduce how to integrate Lightning CSS into a Vite project.

What is Lightning CSS

What exactly is Lightning CSS?

https://lightningcss.dev/

An extremely fast CSS parser, transformer, bundler, and minifier.

Simply put, it is a tool that handles the roles of CSS Parser, Transformer, Bundler, and Minifier.
Written in Rust, its build speed even surpasses that of ESBuild.

Lightning CSS lets you use modern CSS features and future syntax today.

As stated here, by introducing Lightning CSS, it becomes possible to use the latest CSS features and future syntax.

For details on which syntaxes are actually supported, please refer to the GitHub documentation. To give an example as of December 5, 2022, you will be able to use features like CSS Nesting and Custom Media Queries.

If you want to try out the features for now, an official Playground is available, so please check it out.

From reading the documentation, I get the impression that it was originally developed for Parcel, but it can be used from JavaScript, CLI, etc., even without Parcel. In this article, I will introduce how to incorporate it into a project as a custom Vite plugin.

Introducing Lightning CSS to Vite

In this article, I will introduce Lightning CSS into a Vite project as a custom Vite plugin.

Creating the Project

First, let's create a Vite project using yarn create vite.
In this article, I will use yarn. Although I haven't tested it, npm should likely work fine as well.

https://ja.vitejs.dev/guide/#creating-your-first-vite-project

Basically, follow the steps above for creating the project.

$ yarn create vite
//...omitted
✔ Project name: … vite-lightningcss
✔ Select a framework: › Vanilla
✔ Select a variant: › TypeScript

I selected vite-lightningcss as the project name (feel free to choose any name), Vanilla for the framework, and TypeScript for the variant.

$ cd vite-lightningcss
$ yarn

Navigate to the project root and install the packages using the yarn command.

$ yarn dev

Once the local server starts with the yarn dev command, the project creation is complete.

Removing Unnecessary Descriptions and Organizing Files

At this stage, the folder structure should look like this:

.
├── index.html
├── node_modules
│   └── ...omitted...
├── package.json
├── public
│   └── vite.svg
├── src
│   ├── counter.ts
│   ├── main.ts
│   ├── style.css
│   ├── typescript.svg
│   └── vite-env.d.ts
├── tsconfig.json
└── yarn.lock

In this article, we will remove unnecessary folders and files and clean up the descriptions.

The public directory, as well as counter.ts and typescript.svg under src, are not needed and will be deleted.

$ rm -r public src/counter.ts src/typescript.svg

Next, rewrite src/main.ts and src/style.css to contain only the minimum required code.

src/main.ts
import './style.css';
src/style.css
* {
  margin: 0;
  padding: 0;
}

Finally, rewrite src/index.html as well.

src/index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Lightning CSS</title>
  </head>
  <body>
    <h1 class="title">Vite + Lightning CSS Sample</h1>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

After these tasks, the folder structure will be as follows:

.
├── index.html
├── node_modules
│   └── ...omitted...
├── package.json
├── src
│   ├── main.ts
│   ├── style.css
│   └── vite-env.d.ts
├── tsconfig.json
└── yarn.lock

Creating the Plugin

Now that the preparation is complete, let's start creating the plugin.

https://ja.vitejs.dev/guide/api-plugin.html

Please refer to the link above for details.

First, let's install the necessary modules in advance.

$ yarn add -D lightningcss browserslist @types/node

We are installing not only lightningcss but also browserslist to simplify the target browser specification. While it's possible to specify target browsers with lightningcss alone, it can be a bit complicated, so we will use browserslist.

Next, create vite.config.ts in the project root and add the following description.

$ touch vite.config.ts
src/vite.config.ts
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [],
});

Next, create plugins/vite-plugin-lightningcss.ts to describe the plugin process.

$ mkdir plugins
$ touch plugins/vite-plugin-lightningcss.ts

The Vite Plugin API provides several build hooks, similar to rollup.js. Since we are using Lightning CSS to transform the CSS, we can use the transform hook for this process.

https://rollupjs.org/guide/en/#transform

Instructions on how to use Lightning CSS can be found below.

https://github.com/parcel-bundler/lightningcss#from-node

Based on the above, the logic in the plugin is written as follows.

plugins/vite-plugin-lightningcss.ts
import browserslist from 'browserslist';
import {
  transform as CSSTransform,
  browserslistToTargets as CSSBrowserslistToTargets,
} from 'lightningcss';
import { type Plugin } from 'vite';

const cssRegex = /\.(css)$/;
// Specify targets using browserslist
const browserTargets = CSSBrowserslistToTargets(browserslist('6>= 0.25%'));

const vitePluginLightningcss = (): Plugin => {
  return {
    // Name it using the vite-plugin-* convention
    name: 'vite-plugin-lightningcss',
    // CSS transformation process with the transform hook
    transform(src, id) {
      // Process CSS files
      if (cssRegex.test(id)) {
        // Refer to the link above for options
        // https://github.com/parcel-bundler/lightningcss/blob/master/node/index.d.ts
        const { code, map } = CSSTransform({
          filename: id,
          code: Buffer.from(src),
          targets: browserTargets,
          // Set nesting and customMedia to true as they are false by default
          drafts: {
            nesting: true,
            customMedia: true,
          },
        });

        return {
          code: code.toString(),
          map: map?.toString(),
        };
      }

      // Return without processing for non-CSS files
      return {
        code: src,
      };
    },
  };
};

export default vitePluginLightningcss;

Please note that in this article, CSS Nesting and Custom Media Queries are set to true.
The implementation of the plugin is complete. Now, we will load the created plugin in vite.config.ts.

src/vite.config.ts
import { defineConfig } from 'vite';
import vitePluginLightningcss from './plugins/vite-plugin-lightningcss';

export default defineConfig({
  // Load the created plugin
  plugins: [vitePluginLightningcss()],
});

Applying Styles

Now that we have come this far, let's start the local server with yarn dev.

<!-- ...omitted... -->
<body>
  <h1 class="title">Vite + Lightning CSS Sample</h1>
  <script type="module" src="/src/main.ts"></script>
</body>
<!-- ...omitted... -->

Currently, the HTML file has the description above, so if the text "Vite + Lightning CSS Sample" is displayed, it's working correctly.

Now, let's try to see if we can actually use future CSS syntax.

src/style.css
@custom-media --narrow-window (max-width: 600px);

* {
  margin: 0;
  padding: 0;
}
/* CSS Nesting Module */
/* https://www.w3.org/TR/css-nesting-1/ */
body {
  color: red;
  .title {
    color: green;
  }
}
/* Custom Media Queries */
/* https://www.w3.org/TR/mediaqueries-5/#custom-mq */
@media (--narrow-window) {
  body {
    .title {
      color: blue;
    }
  }
}

The above is a description incorporating CSS Nesting and Custom Media Queries. When this style is applied, it will be displayed as follows:

When the viewport width is 590px, the text color becomes blue.
Image showing text color is blue at window width 590px

When the viewport width is 610px, the text color becomes green.
Image showing text color is green at window width 610px

As you can see from the images, CSS Nesting and Custom Media Queries are being reflected.

In this state, let's try building once with the yarn build command.
An arbitrary CSS file will be generated under dist/assets. Checking its content, you can see that the CSS has been transformed as follows:

dist/assets/index.*.css
* {
  margin: 0;
  padding: 0;
}
body {
  color: red;
}
body .title {
  color: green;
}
@media (max-width: 600px) {
  body .title {
    color: #00f;
  }
}

With this, we have successfully integrated Lightning CSS into Vite.

Sample Code

The results of the work performed in this article are available in the following repository. If you would like to check the entire code, please refer to the link below.

https://github.com/yend724/vite-lightningcss-sample

Conclusion

Lightning CSS can be easily used with tools other than Parcel. It allows you to easily try out the latest or future CSS features and syntax, so please give it a try if you are interested.

References

https://lightningcss.dev/
https://vitejs.dev/

Discussion