Git Product home page Git Product logo

vite-plugin-standard-css-modules's Introduction

vite-plugin-standard-css-modules

NPM Downloads ISC License GitHub PRs Welcome
TypeScript Prettier EditorConfig

Provides a CSSStyleSheet or a CSSResult (Lit) for use with import attributes.
Using the "with" keyword and "type : css".


Allows:

import myStyles1 from './my-styles-1.css' with { type: 'css' };
import myStyles2 from './my-styles-2.css' assert { type: 'css' }; // ⚠️ Deprecated
import myStyles3 from './my-styles-3.css'; // ⚠️ Non-standard

To be imported seamlessly, from your project or a dependency (mono-repo…).


The API ensures strict defaults while allowing opt-in flexibility, especially for catering to Node usage.

Installation

npm i vite-plugin-standard-css-modules

Vite or compatible frameworks configuration:

import { standardCssModules } from 'vite-plugin-standard-css-modules';

const myEnvironmentViteConfig = {
	// ...

	plugins: [
		standardCssModules({
			/* transformationMode: "CSSResult", */

			filter: (params) => {
				// console.log({ params });

				// if (filePath === "foo") return false;
				// if (params.ssr) return false;

				return true;
			},

			/* log: false, */

			ssrOnlyLit: true, // Removes the need for `?lit`, server-side.
		}),
	],
};

Configuration

transformationMode

CSSStyleSheet (default) is agnostic, and platform-native.
Might not work with SSR until JS server runtimes support this API or a working minimal implementation.

CSSResult is Lit-specific. On the client, it can lazily provide a CSSStyleSheet.
Works with SSR.

filter

(params: { id: string; importer?: string; ssr?: boolean }): boolean => myMatcher(filePath, myPatterns)

Provides a callback for selective CSS file handling.
From there, you can use your favorite glob paths matcher, like picomatch, minimatch…
ssr is true when the import is from a server-side context.

This hook is useful if you have some non-standards CSS imports you want to preserve, by migrating to the standard syntax, gradually.

ssrOnlyLit

boolean (default: false)

Removes the need for the ?lit query on the server to get a usable asset. By opting in, you'll get a CSSStyleSheet client side and a CSSResult while on the server-side, automatically.
All by using the same bare, query-less import (e.g. ./my-styles.css).

Import flags

?lit

This plugin aims to get rid of non-standard import queries.
However, you'll find yourself obliged to use a CSSResult in a Node setup.
Until a leaner solution emerges, you can add the ?lit flag on a per-file basis.
This can be useful if you want to do server-side-only stuff with some client-side leaves deeper in the tree, whereas the transformationMode shown above is all or nothing.

For some reasons, like isomorphism, you might want a CSSResult on the client-side, but it's not needed otherwise. Lit handles those two shapes just fine, without intermediary steps.
It's possible to mix and fit them in the static styles of your custom element.

SSR considerations with CSSStyleSheet

If no DOM shims are present in your JS server runtime, you'll get a CSSStyleSheet is not defined.
With a DOM Shim (like the Lit SSR's one), you'll get a replaceSync method is not defined, because the CSSStyleSheet global object is empty.
Solution: use CSSResult here.

Environments

  • Vite 5
  • Vite 5 SSR (ssrModuleLoader)
  • Astro 4 Client side JS
  • Astro 4 Server side JS

Tested with Node 20 (LTS) and 2024 majors browsers.
Firefox / Safari / Chromium are all supporting constructable stylesheets.

TypeScript

IDE awareness

// ./src/vite-env.d.ts
// or
// ./src/env.d.ts

// Add this reference:
/// <reference types="vite-plugin-standard-css-modules/css-modules" />
// (Order matters with Astro)

/// <reference types="vite/client" />
//              (Or `astro/client`)

That way,

import myElementStyles from './my-element.css' with { type: 'css' };
import myElementStyles from './my-element.css?lit' with { type: 'css' };
  • ./my-element.css will be casted as CSSStyleSheet
  • ./my-element.css?lit will be casted as CSSResult

You can also append them manually in your env.d.ts, see css-modules.d.ts.

Demo

Check out the demo folder.

You'll find an Astro minimal setup, which works exactly the same as with this vite-lit-ssr demo project.

I updated to the latest Lit 3 and Vite 5, and with minor Lit SSR syntax adaption, tested it successfully.

Both of these setups, Homebrewed Lit SSR and Astro, are using ssrLoadModuleLoader.
Basically, you'll get an isomorphic experience thanks to Vite internal tooling which is smoothening environment gaps, minus unresolved DOM limitations in Node.

How it works?

file.css redirects to file.css?raw which by-pass all specific Vite handling.
Then file.css?inline is requested and injected back. This means you should get your usual Vite CSS handling at the end (think all the post-css stuff).


Since the result is handled like any ?raw imported module with Vite, it's not a "real", living CSS module.
See the rollup-plugin-css-modules documentation for more details about expected limitations, which are shared conceptually, with vite-plugin-standard-css-modules.

Footnotes

100% ESM, dependency-free.

You just need the optional lit peer-dependency, if you're using CSSResult over the default CSSStyleSheet.


See also rollup-plugin-css-modules.
Its documentation will bring you insights into the state of this API proposal.


Other projects 👀


Find this project useful?

GitHub


🔗  JulianCataldo.com

vite-plugin-standard-css-modules's People

Contributors

juliancataldo avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

vite-plugin-standard-css-modules's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.