React TypeScript项目导入SCSS模块时提示‘Cannot find module './styles.scss' or its corresponding type declarations’错误的求助
Hey there, this is a super common issue when using Sass with TypeScript in Create React App—TypeScript doesn’t know how to handle .scss files out of the box, so we just need to add a type declaration to fix it. Here’s how to do it step by step:
Option 1: Add a dedicated SCSS type declaration file
Create a
typesfolder inside your project’ssrcdirectory (storing it insrckeeps things organized).Inside that folder, make a new file named
scss.d.tsand paste this code:declare module '*.scss' { const styles: { [key: string]: string }; export default styles; }This tells TypeScript that any file ending with
.scssexports an object where keys are your original class names (likeApp) and values are the hashed class names generated by CSS Modules.Double-check your
tsconfig.jsonto ensure theincludefield covers this file. If you have"src/**/*"listed, you’re all set—TypeScript will automatically scan and recognize the declaration.
Option 2: Use the existing react-app-env.d.ts file
If you don’t want to create a separate types folder, you can drop the same module declaration directly into the react-app-env.d.ts file that Create React App generates by default in your src directory. Just paste the code into that file, and you’re good to go.
Quick note on CSS Modules
Your current code uses CSS Modules (importing styles as an object), which is exactly how CRA expects you to use scoped styles. If you ever want to import a global stylesheet (without hashed class names), just use import './styles.scss' without assigning it to a variable—TypeScript won’t throw an error for that scenario either.
After setting up the type declaration, restart your dev server if it’s running, and the error should vanish immediately.
内容的提问来源于stack exchange,提问作者Durfingo005

