Use CSS Modules in React components with Typescript built by webpack

↘锁芯ラ 提交于 2019-11-29 01:19:11

import has special meaning to TypeScript. It means that TypeScript will attempt to load and understand the thing being imported. The right way is to define require like you mentioned but then var instead of import:

var styles = require('../../../css/tree.css')`
  1. Declare 'require' as per ts-loader documentation.
  2. Use 'require' as generic with < any > type: require< any >("../../../css/tree.css").

*.d.ts file

declare var require: {
   <T>(path: string): T;
   (paths: string[], callback: (...modules: any[]) => void): void;
   ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
}; 

*.tsx file with component

const styles = require<any>("../../../css/tree.css");
...
<h3 className={styles.h3}>Components</h3>

I know it was already answered, but I was struggling with it for a while before I realized I need to use generic type specification, without that I wasn't able to access content of CSS file. (I was getting error: Property 'h3' does not exists on type '{}'.)

I had similar problem. For me, works import:

import '../../../css/tree.css';

Webpack change this like any other normal imports. It change it to

__webpack_require__(id)

One drawback is that you lost control on style variable.

You can use https://github.com/Quramy/typed-css-modules, which creates .d.ts files from CSS Modules .css files. Please see also https://github.com/css-modules/css-modules/issues/61#issuecomment-220684795

A bit late to game but you can create a file called tree.css.d.ts in the same folder as tree.css that has this line:

export const h3: string;

and still use the import statement import * as styles from ... and you will still getcode completion and compile time checking.

You can either manage these definition files manually or you could integrate typed-css-modules into your build pipeline (https://github.com/Quramy/typed-css-modules)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!