Cannot Find Module 'XXX.scss' or Its Corresponding Type Declarations

Question

When using CSS Module in Typescript + Webpack + Sass projects, you can use CSS modules normally, but vscode always prompts cannot find module'XXX.scss' or its corresponding type declarations.

Solution

Option 1

  1. First of all, make sure that webpack and sass have been able to recognize the CSS Module, please refer to the webpack official website configuration.

    Separating Interoperable CSS-only and CSS Module features

  2. Configure d.ts

    Here comes the important part, we should pay attention to the configuration of two d.ts files

    • Main file index.d.ts
      declare module'*.scss' {
          const content: {[key: string]: any}
          export = content
      }
      
    • Add another typings.d.ts file to the same level directory
      declare module'*.scss';
      

After this configuration, my problem has been solved, and neither VSCODE nor Node command line interface will report an error, and it can match normally.

Option 2

The recommended solution on the Internet is to write the d.ts file in the same level directory of the css file, usually using a plug-in to automatically complete

Choose one of the following plugins

Usually after installing the plug-in to automatically generate each css declaration file, there will be no error, but there are two shortcomings, one is that there are too many project files, and the other is that the path alias is still not recognized by VSCODE (the Node command line is normal), this Two d.ts must be configured as above to prevent VSCODE from prompting errors.

Reference

  • Some possible scss file declarations
//example one
declare module'*.scss';

//example two
declare module'*.scss' {
    const content: any;
    export default content;
}

//example three
declare module'*.scss' {
    const content: Record<string, string>;
    export default content;
}

//example four
declare module'*.scss' {
    const content: {[key: string]: any}
    export = content
}

Comments