Typescript: Add support to CSS modules

Created on 21 Jan 2018  路  4Comments  路  Source: microsoft/TypeScript

Typescript can not recognize CSS file, so it self can't support CSS modules, when I type this:

import React from 'react';
import styles from './style.css';

const Button = () => {
     return (
         <button className={styles.myButtonClass}>click me</button>
     )
}

It will cause:

Cannot find module './style.css'.

Could you please add support for CSS modules?

Question

Most helpful comment

This is already supported, see https://www.typescriptlang.org/docs/handbook/modules.html#wildcard-module-declarations

in your case, you need to add something like the following in a globaltypes.d.ts (name not important), which you include in your project.

declare module "*.css" {
declare const css: string;
export = css;
}

All 4 comments

This is already supported, see https://www.typescriptlang.org/docs/handbook/modules.html#wildcard-module-declarations

in your case, you need to add something like the following in a globaltypes.d.ts (name not important), which you include in your project.

declare module "*.css" {
declare const css: string;
export = css;
}

Excuse me again, but how could I include wildcard modules into my project? This is my config:

"compilerOptions": {
    ...
    "typeRoots": ["./"],
    "types": ["global.d.ts"]
}  

And this is my definition:

declare module "*.css" {
    declare const css: string;
    export = css;
}

And I import CSS file:

import styles from './style.css!css';

It still doesn't work and will also yells me:

Cannot find type definition file for 'global.d.ts'.
// globals.d.ts
declare module "*.css!css" {
  const css: string;
  export default css;
}

Also note that adding the file to typeRoots is not necessary and may have unintended consequences as that property is generally only used for third party declarations.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wmaurer picture wmaurer  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments

bgrieder picture bgrieder  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

blendsdk picture blendsdk  路  3Comments