简体   繁体   中英

"Cannot find module './something.module.scss' or its corresponding type declarations

I'm trying to use scss modules with react typescript. This feature should be baked into React from react-scripts@2.0.0 and higher as it says on their website .

For typescript support and intellisense, I am using the typescript-plugin-css-modules module.

Hovering over css imports for classnames work just fine:

将鼠标悬停在 css 导入上,显示智能感知类名

Here's my code:


src/pages/homePage/homePage.tsx

import styles from './styles.module.scss';
 
const HomePage = () => {
    return <div className={styles.myStyle}>Home page</div>;
};
    
export default HomePage;

src/pages/homePage/styles.module.scss

.myStyle {
    color: red;
}

Error message on screen:

网站上的错误信息

As you can see, the color is correct in the background, and dismissing the error makes the website work just fine. Therefore, it is safe to assume that the error is only made by typescript. I have seen articles about this, like this one where they declare a style.d.ts file in the module root dir, for declaring css modules, with something like this inside:

// For SCSS
declare module "*.module.scss" {
  const classes: { [key: string]: string };
  export default classes;
}

However, this produces an error as classes is already defined, because this file is already created by react scripts:

node_modules/react-scripts/lib/react-app.d.ts

[...]

declare module '*.module.scss' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

[...]

So, since react-scripts already create these for me, and I am using the typescript-plugin-css-modules module, everything should be fine. I am not receiving any red lines or errors in the code editor, only in the website.

I hope someone has a solution, thanks in advance!

I found the answer. I accidentally deleted react-app-env.d.ts after using create-react-app. This must exist in order to use CSS modules. If your project is also missing this file. Add it to your src folder and write

/// <reference types="react-scripts" />

As far as I know, you can use module.scss but u should import style from module.css, not module.scss. It works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM