mizdra / happy-css-modules

Typed, definition jumpable CSS Modules. Moreover, easy!
MIT License
217 stars 5 forks source link

Feature: Dependent Type Definition File #106

Closed mizdra closed 1 year ago

mizdra commented 1 year ago

Background

The current format of the type definition file (.css.d.ts) is as follows:

// 1.css.d.ts
declare const styles: {
  readonly "a": string; // from 1.css
  readonly "a": string; // from 2.css
  readonly "b": string; // from 2.css
  readonly "c": string; // from 3.css
};

.css.d.ts contains tokens imported from several .css files.

It is not enough to parse .css.d.ts to know from which file the tokens came. We must also analyze the .css.d.ts.map.

As a side note, we hope to provide a stylelint rule in the future that warns about unused tokens. To implement this rule, we will implement an algorithm using the TypeScript Compiler API to search unused tokens from .ts.

Since it is difficult to parse .css.d.ts.map using the TypeScript Compiler API, it is useful if the .css.d.ts file contains information about the origin of the tokens.

Proposal

Therefore, we would like to change the format of the type definition file as follows:

// 1.module.css.d.ts
declare const styles:
  & Readonly<{ "a": string }> // from 1.css
  & Readonly<Pick<typeof import("./2.css"), "a">> // from 2.css
  & Readonly<Pick<typeof import("./2.css"), "b">> // from 2.css
  & Readonly<Pick<typeof import("./3.css"), "c">> // from 3.css
;

Now we can know the origin of the tokens simply by parsing the .css.d.ts.

Since the .css.d.ts of the external library's css file does not exist, the tokens derived from that css file must be extracted to the import source.

šŸ™… incorrect:

// 1.css.d.ts
declare const styles:
  & Readonly<{ "a": string }> // from 1.css
  & Readonly<Pick<typeof import("bootstrap/index.css"), "a">> // from bootstrap/index.css
;

šŸ™†ā€ā™€ļø correct:

// 1.css.d.ts
declare const styles:
  & Readonly<{ "a": string }> // from 1.css
  & Readonly<{ "a": string }> // from bootstrap/index.css
;

PoC

https://github.com/mizdra/enhanced-typed-css-modules/pull/64/files#diff-781dc6a939096f9f08f21e961037b84859773aa215af6cd2940a2654f47a4037