• Stars
    star
    918
  • Rank 48,050 (Top 1.0 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Creates .d.ts files from CSS Modules .css files

typed-css-modules github actions npm version

Creates TypeScript definition files from CSS Modules .css files.

If you have the following css,

/* styles.css */

@value primary: red;

.myClass {
  color: primary;
}

typed-css-modules creates the following .d.ts files from the above css:

/* styles.css.d.ts */
declare const styles: {
  readonly primary: string;
  readonly myClass: string;
};
export = styles;

So, you can import CSS modules' class or variable into your TypeScript sources:

/* app.ts */
import styles from './styles.css';
console.log(`<div class="${styles.myClass}"></div>`);
console.log(`<div style="color: ${styles.primary}"></div>`);

CLI

npm install -g typed-css-modules

And exec tcm <input directory> command. For example, if you have .css files under src directory, exec the following:

tcm src

Then, this creates *.css.d.ts files under the directory which has original .css file.

(your project root)
- src/
    | myStyle.css
    | myStyle.css.d.ts [created]

output directory

Use -o or --outDir option.

For example:

tcm -o dist src
(your project root)
- src/
    | myStyle.css
- dist/
    | myStyle.css.d.ts [created]

file name pattern

By the default, this tool searches **/*.css files under <input directory>. If you can customize glob pattern, you can use --pattern or -p option. Note the quotes around the glob to -p (they are required, so that your shell does not perform the expansion).

tcm -p 'src/**/*.icss' .

watch

With -w or --watch, this CLI watches files in the input directory.

validating type files

With -l or --listDifferent, list any files that are different than those that would be generated. If any are different, exit with a status code 1.

camelize CSS token

With -c or --camelCase, kebab-cased CSS classes(such as .my-class {...}) are exported as camelized TypeScript varibale name(export const myClass: string).

You can pass --camelCase dashes to only camelize dashes in the class name. Since version 0.27.1 in the webpack css-loader. This will keep upperCase class names intact, e.g.:

.SomeComponent {
  height: 10px;
}

becomes

declare const styles: {
  readonly SomeComponent: string;
};
export = styles;

See also webpack css-loader's camelCase option.

named exports (enable tree shaking)

With -e or --namedExports, types are exported as named exports as opposed to default exports. This enables support for the namedExports css-loader feature, required for webpack to tree shake the final CSS (learn more here).

Use 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).

When this option is enabled, the type definition changes to support named exports.

NOTE: this option enables camelcase by default.

.SomeComponent {
  height: 10px;
}

Standard output:

declare const styles: {
  readonly SomeComponent: string;
};
export = styles;

Named exports output:

export const someComponent: string;

API

npm install typed-css-modules
import DtsCreator from 'typed-css-modules';
let creator = new DtsCreator();
creator.create('src/style.css').then(content => {
  console.log(content.tokens); // ['myClass']
  console.log(content.formatted); // 'export const myClass: string;'
  content.writeFile(); // writes this content to "src/style.css.d.ts"
});

class DtsCreator

DtsCreator instance processes the input CSS and create TypeScript definition contents.

new DtsCreator(option)

You can set the following options:

  • option.rootDir: Project root directory(default: process.cwd()).
  • option.searchDir: Directory which includes target *.css files(default: './').
  • option.outDir: Output directory(default: option.searchDir).
  • option.camelCase: Camelize CSS class tokens.
  • option.namedExports: Use named exports as opposed to default exports to enable tree shaking. Requires import * as style from './file.module.css'; (default: false)
  • option.EOL: EOL (end of line) for the generated d.ts files. Possible values '\n' or '\r\n'(default: os.EOL).

create(filepath, contents) => Promise(dtsContent)

Returns DtsContent instance.

  • filepath: path of target .css file.
  • contents(optional): the CSS content of the filepath. If set, DtsCreator uses the contents instead of the original contents of the filepath.

class DtsContent

DtsContent instance has *.d.ts content, final output path, and function to write file.

writeFile(postprocessor) => Promise(dtsContent)

Writes the DtsContent instance's content to a file. Returns the DtsContent instance.

  • 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.

    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:

    dtsContent.writeFile(definition => `// Generated automatically, do not edit\n${definition}`);

tokens

An array of tokens retrieved from input CSS file. e.g. ['myClass']

contents

An array of TypeScript definition expressions. e.g. ['export const myClass: string;'].

formatted

A string of TypeScript definition expression.

e.g.

export const myClass: string;

messageList

An array of messages. The messages contains invalid token information. e.g. ['my-class is not valid TypeScript variable name.'].

outputFilePath

Final output file path.

Remarks

If your input CSS file has the following class names, these invalid tokens are not written to output .d.ts file.

/* TypeScript reserved word */
.while {
  color: red;
}

/* invalid TypeScript variable */
/* If camelCase option is set, this token will be converted to 'myClass' */
.my-class {
  color: red;
}

/* it's ok */
.myClass {
  color: red;
}

Example

There is a minimum example in this repository example folder. Clone this repository and run cd example; npm i; npm start.

Or please see https://github.com/Quramy/typescript-css-modules-demo. It's a working demonstration of CSS Modules with React and TypeScript.

License

This software is released under the MIT License, see LICENSE.txt.

More Repositories

1

tsuquyomi

A Vim plugin for TypeScript
Vim Script
1,384
star
2

lerna-yarn-workspaces-example

How to build TypeScript mono-repo project with yarn and lerna
TypeScript
893
star
3

ts-graphql-plugin

TypeScript Language Service Plugin for GraphQL developers
TypeScript
674
star
4

electron-connect

Livereload tool for Electron
JavaScript
339
star
5

npm-ts-workspaces-example

Monorepos example project using npm workspaces and TypeScript project references
TypeScript
296
star
6

jest-prisma

Jest environment for integrated testing with Prisma client
TypeScript
245
star
7

typescript-eslint-language-service

TypeScript language service plugin for ESLint
TypeScript
243
star
8

prisma-fabbrica

Prisma generator to define model factory
TypeScript
221
star
9

eslint-plugin-tutorial

A tutorial/template repository to explain how to create your eslint plugins
TypeScript
190
star
10

gql-study-workshop

TypeScript
144
star
11

vim-js-pretty-template

highlights JavaScript's Template Strings in other FileType syntax rule
Vim Script
143
star
12

electron-jsx-babel-boilerplate

Electron boilerplate with React.js and babel
JavaScript
118
star
13

vison

A Vim plugin for writing JSON with JSON Schema
Vim Script
96
star
14

zisui

Yet another CLI to screenshot your Storybook
TypeScript
72
star
15

angular-puppeteer-demo

A demonstration repository explains how to using Puppeteer in unit testing
TypeScript
58
star
16

pico-ml

A toy programming language which is a subset of OCaml.
TypeScript
50
star
17

x-img-diff

Detect structural difference information of 2 images considering into translation
C++
47
star
18

graphql-decorator

TypeScript
43
star
19

apollo-link-fragment-argument

An Apollo Link to enable to parameterize fragments
TypeScript
40
star
20

better-name

CLI tool to move JavaScript(ES2015) or TypeScript module files
TypeScript
34
star
21

type-dungeon

TypeScript code exercise
TypeScript
31
star
22

talt

Template functions to generate TypeScript AST node object
TypeScript
28
star
23

ngx-typed-forms

Extends Angular reactive forms strongly typed
TypeScript
27
star
24

loadable-ts-transformer

TypeScript custom transformer for loadable-components SSR
TypeScript
26
star
25

typescript-css-modules-demo

A working demo of CSS Modules, using TypeScript, css-modulesify and typed-css-modules
TypeScript
25
star
26

angular2-load-children-loader

A webpack loader for ng2 lazy loading
JavaScript
23
star
27

electron-disclosure

Sample electron app
JavaScript
22
star
28

ng2-lazy-load-demo

A sample repository for Angular2 lazy module loading
TypeScript
22
star
29

opencv-wasm-knnmatch-demo

Web Assembly OpenCV Feature Matching Demonstration
JavaScript
21
star
30

ionic-apollo-simple-app

Explains how to develop Ionic application with Apollo GraphQL client
TypeScript
19
star
31

ngx-zombie-compiler

Fast JiT compiler for Angular testing
TypeScript
15
star
32

decode-tiff

⚡ A lightweight JavaScript TIFF decoder 🎨
JavaScript
15
star
33

ts-server-side-anatomy

Explain what TypeScript server(tsserver) does under your editors
TypeScript
15
star
34

tsuquyomi-vue

vim plugin for TypeScript and Vue.js
Vim Script
15
star
35

generator-ngdoc

Yeoman generator for AngularJS's module documentation
JavaScript
14
star
36

ts-playground-plugin-vim

TypeScript Playground plugin for Vim keybindings
TypeScript
12
star
37

prisma-yoga-example

GraphQL server example using Prisma and graphql-yoga
TypeScript
12
star
38

tsc-react-example

Example to compile React JSX with TypeScript
JavaScript
10
star
39

puppeteer-example

JavaScript
10
star
40

angular-recursive

AngularJS directives for recursive data.
JavaScript
9
star
41

nirvana-js

⚡ JavaScript file runner using Electron
TypeScript
9
star
42

dgeni-ngdocs-example

JavaScript
7
star
43

rxdb-simple-chat-app

simple chat application using RxDB
JavaScript
7
star
44

falcor-firebase

It provides a Falcor datasource from your Firebase database
JavaScript
7
star
45

swagger-codegen-customize-sample

A sample repository for customize swagger-codegen
HTML
6
star
46

zakki

6
star
47

falcor-lambda

creates AWS Lambda handler from Falcor's data source
JavaScript
6
star
48

angular-karma-chrome-headless-demo

TypeScript
6
star
49

server-components-with-container-presentation

TypeScript
6
star
50

storycov

TypeScript
5
star
51

prisma2-nexus-example

TypeScript
5
star
52

screenshot-testing-demo-ngjp18

Demonstration repository "Screenshot test with Angular" session ng-japan18
TypeScript
5
star
53

apollo-angular-example

An example repository to explain how to integrate Apollo and Angular
TypeScript
5
star
54

serverless-falcor-starter

A Serverless project including Falcor routing.
JavaScript
5
star
55

vim-dtsm

A Vim plugin to execute TypeScript dtsm command
Vim Script
4
star
56

dotfiles

settings
Vim Script
4
star
57

arlecchino

TypeScript
4
star
58

angular-sss-demo

Storybook, Screenshot, and Snapshot testing for Angular
TypeScript
4
star
59

graphql-script-sample

Shell script GraphQL client for GitHub v4 API sample
Shell
3
star
60

storybook-angular-cli-helper

TypeScript
3
star
61

storyshots-with-portal-repro

JavaScript
3
star
62

simple-coverage-diff-action

TypeScript
3
star
63

fretted-strings

Mark on your strings and get it's position
TypeScript
3
star
64

face_of_the_year

Python
3
star
65

vim-json-schema-nav

Vim Script
3
star
66

apollo-sandbox

TypeScript
2
star
67

ts-react-css-modules-example

A sample repository for React JSX with CSS Modules for TypeScript
TypeScript
2
star
68

graphql-streaming-example

GraphQL @defer/@stream example
TypeScript
2
star
69

tsjp-resources

TypeScript
2
star
70

karma-nightmare-angular-demo

A working demonstration for visual regression testing of Angular application.
TypeScript
2
star
71

react-apollo-ssr-demo

TypeScript
2
star
72

eslint-plugin-unlearned-kanji

TypeScript
2
star
73

react-css-note

HTML
2
star
74

inspectorium

Inspect your GitHub source code
TypeScript
2
star
75

example-of-generator-ngdoc

An example repository of generator-ngdoc(an Yeoman generator)
JavaScript
2
star
76

test-with-aot-summary

Explains how to Angular's AOT result in unit testing
TypeScript
2
star
77

copl-ts

CoPL本のTypeScript実装
TypeScript
2
star
78

astsx

TypeScript
2
star
79

prignore

Chrome-extension for GitHub PR
JavaScript
2
star
80

abacus-ts

Calculator implemented by only TypeScript type operation
TypeScript
1
star
81

puppeteer-coverage-study

TypeScript
1
star
82

pkg-study

JavaScript
1
star
83

sewordle

A chrome extension which generates tag cloud using user query keywords inputed at search-engine.
JavaScript
1
star
84

react-falcor-demo

Demonstration of Falcor and React
TypeScript
1
star
85

nopmdcheck

A jenkins plugin to check "NOPMD" comments in workspace.
JavaScript
1
star
86

type-apollo-local-state

TypeScript
1
star
87

fuse-postcss-example

A Fuse-Box with PostCSS example repository.
CSS
1
star
88

ts-api-study

TypeScript
1
star
89

dotson

TypeScript
1
star
90

prisma-dmmf-viewer

Display Prisma DMMF(Data Model Meta Format)
JavaScript
1
star
91

typescript-api-tutrial

1
star
92

first-liquidfun

JavaScript
1
star
93

apollo-client-37-study

TypeScript
1
star
94

ccvsample

JavaScript
1
star
95

ossc-hackathon-ardrone-14

JavaScript
1
star
96

Quramy

1
star
97

crudsample

this is a sample application on node (express + mongoose).
JavaScript
1
star
98

reproduce-apollo-react-memleak

To reproduce react-apollo memory leak
TypeScript
1
star
99

groovy-labo

Groovy
1
star
100

es7study

JavaScript
1
star