1.2.0 • Published 3 years ago

css-typings-loader v1.2.0

Weekly downloads
5
License
MIT
Repository
github
Last release
3 years ago

css-typings-loader

Tiny webpack loader to generate TypeScript typings for CSS modules, no complex configuration, support other css preprocessors(less, sass, ...), easy to use.

Installation

npm i css-typings-loader

or

yarn add css-typings-loader

Tips

css-typings-loader will convert CSS selector(class/id) names to snake_case style, :global(xxx) will not be converted.

When building for the first time, TypeScript may report errors because the typing files has not been generated yet, when finished, there should be no more errors.

input

.foo { }
.foo-abc { }
.foo_def { }
:global(.abc-def) { }

output

.foo { }
.foo_abc { }
.foo_def { }
.abc-def { }

typings

export interface Styles {
  foo: string;
  foo_abc: string;
  foo_def: string;
}
declare const styles: Styles;
export default styles;

So, the following two names will be converted to the same one, it will cause unexpected results, should be banned.

input

.foo-bar { }
.foo_bar { }

output

.foo_bar { }
.foo_bar { }

typings

export interface Styles {
  foo_bar: string;
}
declare const styles: Styles;
export default styles;

Usage

webpack configuration

{
  test: /\.css$/,
  use: [ 'css-loader?modules', 'css-typings-loader' ],
}

with less

{
  test: /\.less$/,
  use: [ 'css-loader?modules', 'css-typings-loader', 'less-loader' ],
}

React component with TypeScript

Home
  - index.tsx
  - style.less
  - style.less.d.ts

index.tsx

import * as React from 'react'

import style from './style.less'

export default function() {
  return (
    <div className={style.home_wrap}>
      <div className={style.home_title + ' red-title'}>css-typings-loader</div>
      <h2 className={style.home_info}>Thanks for using!</h2>
    </div>
  )
}

style.less

.home-wrap {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  text-align: center;
}

.home-title {
  font-weight: bold;
  font-size: 30px;
  color: #333;
}

.home-info {
  font-size: 20px;
  color: #999;
  font-style: italic;
}

@media (max-width: 800px) {
  :global(.red-title) {
    color: red;
  }
}

style.less.d.ts

This file is automatically generated by css-typings-loader, please do not edit it manually.

export interface Styles {
  home_wrap: string;
  home_title: string;
  home_info: string;
}
declare const styles: Styles;
export default styles;

Here is a complete example