Wednesday, February 5, 2025
HomeProgrammingCompiling CSS With Vite And Lightning CSS

Compiling CSS With Vite And Lightning CSS


Suppose you observe CSS function growth as carefully as we do right here at CSS-Tips. In that case, it’s possible you’ll be like me and keen to make use of many of those wonderful instruments however discover browser help typically lagging behind what could be thought-about “trendy” CSS (no matter meaning).

Even when browser distributors all have a sure function launched, customers may not have the newest variations!

We are able to actually plan for this quite a lot of methods:

  • function detection with @helps
  • progressively enhanced designs
  • polyfills

For even further assist, we flip to construct instruments. Likelihood is, you’re already utilizing some kind of construct instrument in your initiatives as we speak. CSS builders are more than likely acquainted with CSS pre-processors (corresponding to Sass or Much less), however for those who don’t know, these are instruments able to compiling many CSS recordsdata into one stylesheet. CSS pre-processors assist make organizing CSS so much simpler, as you may transfer components of CSS into associated folders and import issues as wanted.

Pre-processors don’t simply present organizational superpowers, although. Sass gave us a loopy record of options to work with, together with:

  • extends
  • features
  • loops
  • mixins
  • nesting
  • variables
  • …extra, in all probability!

For some time, this massive function set supplied a way of filling gaps lacking from CSS, making Sass (or no matter preprocessor you fancy) really feel like a necessity when beginning a brand new venture. CSS has developed so much because the launch of Sass — we now have so a lot of these options in CSS as we speak — so it doesn’t fairly really feel that method anymore, particularly now that we now have native CSS nesting and customized properties.

Together with CSS pre-processors, there’s additionally the idea of put up-processing. This sort of instrument normally helps remodel compiled CSS in several methods, like auto-prefixing properties for various browser distributors, code minification, and extra. PostCSS is the massive one right here, providing you with tons of the way to govern and optimize your code, one other step within the construct pipeline.

In lots of implementations I’ve seen, the construct pipeline usually runs roughly like this:

  1. Generate static property
  2. Construct software recordsdata
  3. Bundle for deployment

CSS is normally dealt with in that first half, which incorporates working CSS pre- and post-processors (although post-processing may also occur after Step 2). As talked about, the continued evolution of CSS makes it much less obligatory for a instrument corresponding to Sass, so we would have a possibility to avoid wasting time.

Vite for CSS

Awarded “Most Adopted Expertise” and “Most Liked Library” from the State of JavaScript 2024 survey, Vite actually appears to be one of many extra fashionable construct instruments accessible. Vite is especially used to construct reactive JavaScript front-end frameworks, corresponding to Angular, React, Svelte, and Vue (made by the identical developer, after all). Because the title implies, Vite is loopy quick and might be as easy or complicated as you want it, and has turn out to be certainly one of my favourite instruments to work with.

Vite is usually regarded as a JavaScript instrument for JavaScript initiatives, however you should utilize it with out writing any JavaScript in any respect. Vite works with Sass, although you continue to want to put in Sass as a dependency to incorporate it within the construct pipeline. Then again, Vite additionally routinely helps compiling CSS with no further steps. We are able to arrange our CSS code how we see match, with no or very minimal configuration obligatory. Let’s verify that out.

We can be utilizing Node and npm to put in Node packages, like Vite, in addition to instructions to run and construct the venture. Should you wouldn’t have node or npm put in, please try the obtain web page on their web site.

Navigate a terminal to a secure place to create a brand new venture, then run:

npm create vite@newest

The command line interface will ask just a few questions, you may preserve it so simple as doable by selecting Vanilla and JavaScript which is able to give you a starter template together with some no-frameworks-attached HTML, CSS, and JavaScript recordsdata to assist get you began.

terminal displaying the output of running the command npm create vite@latest

Earlier than working different instructions, open the folder in your IDE (built-in growth surroundings, corresponding to VSCode) of selection in order that we will examine the venture recordsdata and folders.

If you want to observe together with me, delete the next recordsdata which are pointless for demonstration:

  • property/
  • public/
  • src/
  • .gitignore

We must always solely have the next recordsdata left in out venture folder:

VSCode file browser display two files: index.html and package.json

Let’s additionally substitute the contents of index.html with an empty HTML template:

<!doctype html>

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta title="viewport" content material="width=device-width, initial-scale=1.0" />
	
    <title>CSS Solely Vite Undertaking</title>
  </head>
  <physique>
    <!-- empty for now -->
  </physique>
</html>

One final piece to arrange is Vite’s dependencies, so let’s run the npm set up command:

npm set up
terminal displaying the output of running the command npm install

A brief sequence will happen within the terminal. Then we’ll see a brand new folder referred to as node_modules/ and a package-lock.json file added in our file viewer.

  • node_modules is used to accommodate all package deal recordsdata put in by way of node package deal supervisor, and permits us to import and use put in packages all through our functions.
  • package-lock.json is a file normally used to ensure a growth staff is all utilizing the identical variations of packages and dependencies.
VSCode file browser displaying a node_modules folder, index.html file, package-lock.json file, and a package.json file

We more than likely received’t want to the touch these items, however they’re obligatory for Node and Vite to course of our code in the course of the construct. Contained in the venture’s root folder, we will create a kinds/ folder to comprise the CSS we’ll write. Let’s create one file to start with, important.css, which we will use to check out Vite.

├── public/
├── kinds/
|   └── important.css
└──index.html

In our index.html file, contained in the <head> part, we will embrace a <hyperlink> tag pointing to the CSS file:

<head>
  <meta charset="UTF-8" />
  <hyperlink rel="icon" kind="picture/svg+xml" href="https://css-tricks.com/vite.svg" />
  <meta title="viewport" content material="width=device-width, initial-scale=1.0" />
	
  <title>CSS Solely Vite Undertaking</title>

  <!-- Foremost CSS -->
  <hyperlink rel="stylesheet" href="https://css-tricks.com/compiling-css-with-vite-and-lightning-css/kinds/important.css">
</head>

Let’s add a little bit of CSS to important.css:

physique {
  background: inexperienced;
}

It’s not a lot, but it surely’s all we’ll want in the intervening time! In our terminal, we will now run the Vite construct command utilizing npm:

npm run construct

With the whole lot linked up correctly, Vite will construct issues based mostly on what is obtainable throughout the index.html file, together with our linked CSS recordsdata. The construct can be very quick, and also you’ll be returned to your terminal immediate.

Terminal displaying the output of the command npm run build, including the filesizes of compiled files
Vite will present a short report, showcasing the file sizes of the compiled venture.

The newly generated dist/ folder is Vite’s default output listing, which we will open and see our processed recordsdata. Testing property/index.css (the filename will embrace a novel hash for cache busting), and also you’ll see the code we wrote, minified right here.

VSCode editor displaying a minified CSS file

Now that we all know how you can make Vite conscious of our CSS, we’ll in all probability wish to begin writing extra CSS for it to compile.

As fast as Vite is with our code, continually re-running the construct command would nonetheless get very tedious. Fortunately, Vite offers its personal growth server, which features a stay surroundings with sizzling module reloading, making adjustments seem immediately within the browser. We are able to begin the Vite growth server by working the next terminal command:

npm run dev
Vite development server running in a terminal

Vite makes use of the default community port 5173 for the event server. Opening the http://localhost:5137/ tackle in your browser will show a clean display screen with a inexperienced background.

Arc browser window, navigated to http://localhost:5173, a blank page with a green background

Including any HTML to the index.html or CSS to important.css, Vite will reload the web page to show adjustments. To cease the event server, use the keyboard shortcut CTRL+C or shut the terminal to kill the method.

At this level, you just about know all you must learn about how you can compile CSS recordsdata with Vite. Any CSS file you hyperlink up can be included within the constructed file.

Organizing CSS into Cascade Layers

One of many objects on my 2025 CSS Wishlist is the flexibility to apply a cascade layer to a hyperlink tag. To me, this could be useful to arrange CSS in a significant methods, in addition to effective management over the cascade, with the advantages cascade layers present. Sadly, this can be a fairly tough ask when contemplating the way in which browsers paint kinds within the viewport. This sort of performance is being mentioned between the CSS Working Group and TAG, but it surely’s unclear if it’ll transfer ahead.

With Vite as our construct instrument, we will replicate the idea as a option to arrange our constructed CSS. Contained in the important.css file, let’s add the @layer at-rule to set the cascade order of our layers. I’ll use a few layers right here for this demo, however be at liberty to customise this setup to your wants.

/* kinds/important.css */
@layer reset, layouts;

That is all we’ll want inside our important.css, let’s create one other file for our reset. I’m a fan of my good friend Mayank‘s trendy CSS reset, which is obtainable as a Node package deal. We are able to set up the reset by working the next terminal command:

npm set up @acab/reset.css
Terminal displaying the output of running npm install @acab/reset.css

Now, we will import Mayank’s reset into our newly created reset.css file, as a cascade layer:

/* kinds/reset.css */
@import '@acab/reset.css' layer(reset);

If there are every other reset layer stylings we wish to embrace, we will open up one other @layer reset block inside this file as effectively.

/* kinds/reset.css */
@import '@acab/reset.css' layer(reset);

@layer reset {
  /* customized reset kinds */
}

This @import assertion is used to tug packages from the node_modules folder. This folder just isn’t typically accessible within the constructed, public model of a web site or software, so referencing this would possibly trigger issues if not dealt with correctly.

Now that we now have two recordsdata (important.css and reset.css), let’s hyperlink them up in our index.html file. Contained in the <head> tag, let’s add them after <title>:

<head>
  <meta charset="UTF-8" />
  <hyperlink rel="icon" kind="picture/svg+xml" href="https://css-tricks.com/vite.svg" />
  <meta title="viewport" content material="width=device-width, initial-scale=1.0" />
	
  <title>CSS Solely Vite Undertaking</title>
	
  <hyperlink rel="stylesheet" href="https://css-tricks.com/compiling-css-with-vite-and-lightning-css/kinds/important.css">
  <hyperlink rel="stylesheet" href="https://css-tricks.com/compiling-css-with-vite-and-lightning-css/kinds/reset.css">
</head>

The concept right here is we will add every CSS file, within the order we’d like them parsed. On this case, I’m planning to tug in every file named after the cascade layers setup in the primary.css file. This may occasionally not work for each setup, however it’s a useful method to remember the priority of how cascade layers have an effect on computed kinds when rendered in a browser, in addition to grouping equally related recordsdata.

Since we’re within the index.html file, we’ll add a 3rd CSS <hyperlink> for kinds/layouts.css.

<head>
  <meta charset="UTF-8" />
  <hyperlink rel="icon" kind="picture/svg+xml" href="https://css-tricks.com/vite.svg" />
  <meta title="viewport" content material="width=device-width, initial-scale=1.0" />
	
  <title>CSS Solely Vite Undertaking</title>
	
  <hyperlink rel="stylesheet" href="https://css-tricks.com/compiling-css-with-vite-and-lightning-css/kinds/important.css">
  <hyperlink rel="stylesheet" href="https://css-tricks.com/compiling-css-with-vite-and-lightning-css/kinds/reset.css">
  <hyperlink rel="stylesheet" href="https://css-tricks.com/compiling-css-with-vite-and-lightning-css/kinds/layouts.css">
</head>

Create the kinds/layouts.css file with the brand new @layer layouts declaration block, the place we will add layout-specific stylings.

/* kinds/layouts.css */
@layer layouts {
  /* layouts kinds */
}

For some fast, straightforward, and superior CSS snippets, I are likely to confer with Stephanie EcklesSmolCSS venture. Let’s seize the “Smol intrinsic container” code and embrace it throughout the layouts cascade layer:

/* kinds/layouts.css */
@layer layouts {
  .smol-container {
    width: min(100% - 3rem, var(--container-max, 60ch));
    margin-inline: auto;
  }
}

This highly effective little, two-line container makes use of the CSS min() perform to supply a responsive width, with margin-inline: auto; set to horizontally heart itself and comprise its little one parts. We are able to additionally dynamically modify the width utilizing the --container-max customized property.

Now if we re-run the construct command npm run construct and verify the dist/ folder, our compiled CSS file ought to comprise:

  • Our cascade layer declarations from important.css
  • Mayank’s CSS reset absolutely imported from reset.css
  • The .smol-container class added from layouts.csss

As you may see, we will get fairly far with Vite as our construct instrument with out writing any JavaScript. Nevertheless, if we select to, we will prolong our construct’s capabilities even additional by writing only a little bit of JavaScript.

Put up-processing with LightningCSS

Lightning CSS is a CSS parser and post-processing instrument that has a whole lot of good options baked into it to assist with cross-compatibility amongst browsers and browser variations. Lightning CSS can remodel a whole lot of trendy CSS into backward-compatible kinds for you.

We are able to set up Lightning CSS in our venture with npm:

npm set up --save-dev lightningcss

The --save-dev flag means the package deal can be put in as a growth dependency, because it received’t be included with our constructed venture. We are able to embrace it inside our Vite construct course of, however first, we might want to write a tiny little bit of JavaScript, a configuration file for Vite. Create a brand new file referred to as: vite.config.mjs and inside add the next code:

// vite.config.mjs
export default {
  css: {
    transformer: 'lightningcss'
  },
  construct: {
    cssMinify: 'lightningcss'
  }
};

Vite will now use LightningCSS to rework and minify CSS recordsdata. Now, let’s give it a take a look at run utilizing an oklch colour. Inside important.css let’s add the next code:

/* important.css */
physique {
  background-color: oklch(51.98% 0.1768 142.5);
}

Then re-running the Vite construct command, we will see the background-color property added within the compiled CSS:

/* dist/index.css */
physique {
  background-color: inexperienced;
  background-color: colour(display-p3 0.216141 0.494224 0.131781);
  background-color: lab(46.2829% -47.5413 48.5542);
}

Lightning CSS converts the colour white offering fallbacks accessible for browsers which could not help newer colour varieties. Following the Lightning CSS documentation for utilizing it with Vite, we will additionally specify browser variations to focus on by putting in the browserslist package deal.

Browserslist will give us a option to specify browsers by matching sure situations (strive it out on-line!)

npm set up -D browserslist

Inside our vite.config.mjs file, we will configure Lightning CSS additional. Let’s import the browserslist package deal into the Vite configuration, in addition to a module from the Lightning CSS package deal to assist us use browserlist in our config:

// vite.config.mjs
import browserslist from 'browserslist';
import { browserslistToTargets } from 'lightningcss';

We are able to add configuration settings for lightningcss, containing the browser targets based mostly on specified browser variations to Vite’s css configuration:

// vite.config.mjs
import browserslist from 'browserslist';
import { browserslistToTargets } from 'lightningcss';

export default {
  css: {
    transformer: 'lightningcss',
    lightningcss: {
      targets: browserslistToTargets(browserslist('>= 0.25%')),
    }
  },
  construct: {
    cssMinify: 'lightningcss'
  }
};

There are many methods to increase Lightning CSS with Vite, corresponding to enabling particular options, excluding options we received’t want, or writing our personal customized transforms.

// vite.config.mjs
import browserslist from 'browserslist';
import { browserslistToTargets, Options } from 'lightningcss';

export default {
  css: {
    transformer: 'lightningcss',
    lightningcss:  Options.Colours,
    
  },
  construct: {
    cssMinify: 'lightningcss'
  }
};

For a full record of the Lightning CSS options, try their documentation on function flags.

Is any of this obligatory?

Studying by way of all this, it’s possible you’ll be asking your self if all of that is actually obligatory. The reply: completely not! However I feel you may see the advantages of gaining access to partialized recordsdata that we will compile into unified stylesheets.

I doubt I’d go to those lengths for smaller initiatives, nevertheless, if constructing one thing with extra complexity, corresponding to a design system, I’d attain for these instruments for organizing code, cross-browser compatibility, and completely optimizing compiled CSS.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments