UNPKG

7.01 kBMarkdownView Raw
1# typed-css-modules [![github actions](https://github.com/Quramy/typed-css-modules/workflows/build/badge.svg)](https://github.com/Quramy/typed-css-modules/actions) [![npm version](https://badge.fury.io/js/typed-css-modules.svg)](http://badge.fury.io/js/typed-css-modules)
2
3Creates TypeScript definition files from [CSS Modules](https://github.com/css-modules/css-modules) .css files.
4
5If you have the following css,
6
7```css
8/* styles.css */
9
10@value primary: red;
11
12.myClass {
13 color: primary;
14}
15```
16
17typed-css-modules creates the following .d.ts files from the above css:
18
19```ts
20/* styles.css.d.ts */
21declare const styles: {
22 readonly primary: string;
23 readonly myClass: string;
24};
25export = styles;
26```
27
28So, you can import CSS modules' class or variable into your TypeScript sources:
29
30```ts
31/* app.ts */
32import styles from './styles.css';
33console.log(`<div class="${styles.myClass}"></div>`);
34console.log(`<div style="color: ${styles.primary}"></div>`);
35```
36
37## CLI
38
39```sh
40npm install -g typed-css-modules
41```
42
43And exec `tcm <input directory>` command.
44For example, if you have .css files under `src` directory, exec the following:
45
46```sh
47tcm src
48```
49
50Then, this creates `*.css.d.ts` files under the directory which has original .css file.
51
52```text
53(your project root)
54- src/
55 | myStyle.css
56 | myStyle.css.d.ts [created]
57```
58
59#### output directory
60
61Use `-o` or `--outDir` option.
62
63For example:
64
65```sh
66tcm -o dist src
67```
68
69```text
70(your project root)
71- src/
72 | myStyle.css
73- dist/
74 | myStyle.css.d.ts [created]
75```
76
77#### file name pattern
78
79By the default, this tool searches `**/*.css` files under `<input directory>`.
80If you can customize glob pattern, you can use `--pattern` or `-p` option.
81Note the quotes around the glob to `-p` (they are required, so that your shell does not perform the expansion).
82
83```sh
84tcm -p 'src/**/*.css' .
85```
86
87#### watch
88
89With `-w` or `--watch`, this CLI watches files in the input directory.
90
91#### validating type files
92
93With `-l` or `--listDifferent`, list any files that are different than those that would be generated.
94If any are different, exit with a status code 1.
95
96#### camelize CSS token
97
98With `-c` or `--camelCase`, kebab-cased CSS classes(such as `.my-class {...}`) are exported as camelized TypeScript varibale name(`export const myClass: string`).
99
100You can pass `--camelCase dashes` to only camelize dashes in the class name. Since version `0.27.1` in the
101webpack `css-loader`. This will keep upperCase class names intact, e.g.:
102
103```css
104.SomeComponent {
105 height: 10px;
106}
107```
108
109becomes
110
111```typescript
112declare const styles: {
113 readonly SomeComponent: string;
114};
115export = styles;
116```
117
118See also [webpack css-loader's camelCase option](https://github.com/webpack/css-loader#camelcase).
119
120#### named exports (enable tree shaking)
121
122With `-e` or `--namedExports`, types are exported as named exports as opposed to default exports.
123This enables support for the `namedExports` css-loader feature, required for webpack to tree shake the final CSS (learn more [here](https://webpack.js.org/loaders/css-loader/#namedexport)).
124
125Use this option in combination with https://webpack.js.org/loaders/css-loader/#namedexport and https://webpack.js.org/loaders/style-loader/#namedexport (if you use `style-loader`).
126
127When this option is enabled, the type definition changes to support named exports.
128
129_NOTE: this option enables camelcase by default._
130
131```css
132.SomeComponent {
133 height: 10px;
134}
135```
136
137**Standard output:**
138
139```typescript
140declare const styles: {
141 readonly SomeComponent: string;
142};
143export = styles;
144```
145
146**Named exports output:**
147
148```typescript
149export const someComponent: string;
150```
151
152## API
153
154```sh
155npm install typed-css-modules
156```
157
158```js
159import DtsCreator from 'typed-css-modules';
160let creator = new DtsCreator();
161creator.create('src/style.css').then(content => {
162 console.log(content.tokens); // ['myClass']
163 console.log(content.formatted); // 'export const myClass: string;'
164 content.writeFile(); // writes this content to "src/style.css.d.ts"
165});
166```
167
168### class DtsCreator
169
170DtsCreator instance processes the input CSS and create TypeScript definition contents.
171
172#### `new DtsCreator(option)`
173
174You can set the following options:
175
176- `option.rootDir`: Project root directory(default: `process.cwd()`).
177- `option.searchDir`: Directory which includes target `*.css` files(default: `'./'`).
178- `option.outDir`: Output directory(default: `option.searchDir`).
179- `option.camelCase`: Camelize CSS class tokens.
180- `option.namedExports`: Use named exports as opposed to default exports to enable tree shaking. Requires `import * as style from './file.module.css';` (default: `false`)
181- `option.EOL`: EOL (end of line) for the generated `d.ts` files. Possible values `'\n'` or `'\r\n'`(default: `os.EOL`).
182
183#### `create(filepath, contents) => Promise(dtsContent)`
184
185Returns `DtsContent` instance.
186
187- `filepath`: path of target .css file.
188- `contents`(optional): the CSS content of the `filepath`. If set, DtsCreator uses the contents instead of the original contents of the `filepath`.
189
190### class DtsContent
191
192DtsContent instance has `*.d.ts` content, final output path, and function to write file.
193
194#### `writeFile(postprocessor) => Promise(dtsContent)`
195
196Writes the DtsContent instance's content to a file. Returns the DtsContent instance.
197
198- `postprocessor` (optional): a function that takes the formatted definition string and returns a modified string that will be the final content written to the file.
199
200 You could use this, for example, to pass generated definitions through a formatter like Prettier, or to add a comment to the top of generated files:
201
202 ```js
203 dtsContent.writeFile(definition => `// Generated automatically, do not edit\n${definition}`);
204 ```
205
206#### `tokens`
207
208An array of tokens retrieved from input CSS file.
209e.g. `['myClass']`
210
211#### `contents`
212
213An array of TypeScript definition expressions.
214e.g. `['export const myClass: string;']`.
215
216#### `formatted`
217
218A string of TypeScript definition expression.
219
220e.g.
221
222```ts
223export const myClass: string;
224```
225
226#### `messageList`
227
228An array of messages. The messages contains invalid token information.
229e.g. `['my-class is not valid TypeScript variable name.']`.
230
231#### `outputFilePath`
232
233Final output file path.
234
235## Remarks
236
237If your input CSS file has the following class names, these invalid tokens are not written to output `.d.ts` file.
238
239```css
240/* TypeScript reserved word */
241.while {
242 color: red;
243}
244
245/* invalid TypeScript variable */
246/* If camelCase option is set, this token will be converted to 'myClass' */
247.my-class {
248 color: red;
249}
250
251/* it's ok */
252.myClass {
253 color: red;
254}
255```
256
257## Example
258
259There is a minimum example in this repository `example` folder. Clone this repository and run `cd example; npm i; npm start`.
260
261Or please see [https://github.com/Quramy/typescript-css-modules-demo](https://github.com/Quramy/typescript-css-modules-demo). It's a working demonstration of CSS Modules with React and TypeScript.
262
263## License
264
265This software is released under the MIT License, see LICENSE.txt.