Use CSS Modules in React components with Typescript built by webpack

前端 未结 5 981
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 18:57

I want to use the css-loader with the \'modules\' option of webpack in a React application written in Typescript. This example was my starting point (they are using Babel, w

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 19:31

    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: {
       (path: string): T;
       (paths: string[], callback: (...modules: any[]) => void): void;
       ensure: (paths: string[], callback: (require: (path: string) => T) => void) => void;
    }; 
    

    *.tsx file with component

    const styles = require("../../../css/tree.css");
    ...
    

    Components

    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 '{}'.)

提交回复
热议问题