Olson CloudWorks 🚀

Cant import CSSSCSS modules TypeScript says Cannot Find Module

September 19, 2026

Cant import CSSSCSS modules TypeScript says Cannot Find Module

Encountering the frustrating “Cannot Find Module” error when trying to import CSS/SCSS modules in your TypeScript project can bring your development to a screeching halt. This issue, a common pain point for many developers, arises when TypeScript struggles to resolve the paths to your stylesheet files. It signifies a configuration problem, preventing your application from correctly styling your components and delivering the intended user experience. We will explore the various causes behind this error and provide proven solutions to resolve it effectively. Understanding the root causes, such as incorrect module resolution settings, missing type declarations, or faulty build configurations, is crucial for maintaining a smooth and efficient development workflow, especially when dealing with complex projects that rely heavily on modular CSS or SCSS.

Understanding the “Cannot Find Module” Error

The “Cannot Find Module” error in TypeScript specifically indicates that the compiler cannot locate the specified module during the compilation process. When applied to CSS or SCSS modules, this typically means TypeScript cannot find the necessary type definitions or configurations to understand how to handle these stylesheet imports. This is because TypeScript, by default, only understands JavaScript and TypeScript files; it needs additional instructions to recognize and process other file types like CSS or SCSS. The error itself doesn’t necessarily mean the file is missing, but rather that TypeScript doesn’t know how to interpret it. This lack of understanding prevents TypeScript from generating the correct JavaScript code, ultimately leading to errors when you try to run your application.

Several factors can contribute to this issue. One common cause is the absence of proper type declarations for CSS or SCSS modules. TypeScript relies on these declaration files (.d.ts) to understand the structure and content of imported modules. Without these declarations, TypeScript simply treats the import statement as an attempt to import a JavaScript module that doesn’t exist. Incorrect configurations in your tsconfig.json file can also lead to this error. For instance, if the moduleResolution setting is not configured correctly, or if the baseUrl and paths are not set up to accurately reflect your project’s directory structure, TypeScript may fail to resolve the module paths correctly. According to a Stack Overflow survey, configuration errors are a leading cause of TypeScript compilation issues. Stack Overflow is a great resource for debugging.

Another potential cause lies in the build process itself. If your build tool (e.g., Webpack, Parcel, or Rollup) is not configured to handle CSS or SCSS modules correctly, it may not generate the necessary JavaScript modules that TypeScript expects. This can happen if you’re missing the required loaders or plugins in your build configuration, preventing the build tool from transforming your stylesheets into JavaScript modules that can be imported and used in your TypeScript code. Ensuring your build process properly handles CSS/SCSS is therefore critical for avoiding this error. Additionally, version mismatches between different packages in your project can also cause unexpected behavior, including import errors. Regularly updating your dependencies and ensuring compatibility between different packages can help prevent such issues.

Configuring TypeScript for CSS/SCSS Modules

To successfully import CSS or SCSS modules in your TypeScript project, you need to configure TypeScript to understand how to handle these file types. This primarily involves creating or obtaining type declaration files and configuring your tsconfig.json file appropriately. Let’s start with type declaration files. These files, typically with a .d.ts extension, tell TypeScript the structure and types of the modules you are importing. For CSS/SCSS modules, you can create a global declaration file (e.g., global.d.ts) that tells TypeScript to treat CSS/SCSS imports as modules.

Here’s an example of a basic global.d.ts file:

typescript declare module “.module.css” { const classes: { readonly [key: string]: string }; export default classes; } declare module “.module.scss” { const classes: { readonly [key: string]: string }; export default classes; } This code tells TypeScript that any file ending in .module.css or .module.scss is a module that exports an object where the keys are the class names and the values are the corresponding CSS class strings. This allows you to import CSS modules and access class names in a type-safe manner. The readonly keyword ensures that the class names cannot be modified after import, promoting immutability and preventing accidental mutations. Remember to include this global.d.ts file in your tsconfig.json file under the include or files option.

Next, you need to configure your tsconfig.json file. Key settings to consider include moduleResolution, baseUrl, and paths. The moduleResolution setting tells TypeScript how to resolve modules. For modern projects using module bundlers like Webpack or Parcel, setting this to node or bundler is generally recommended. The baseUrl setting specifies the base directory for resolving non-relative module names. Setting this to your project’s root directory can simplify import paths. The paths setting allows you to create custom module resolution mappings. This can be useful for aliasing commonly used modules or directories. Here’s an example of how to configure these settings:

json { “compilerOptions”: { “moduleResolution”: “node”, “baseUrl”: “./src”, “paths”: { “@components/”: [“components/”] }, “esModuleInterop”: true, “resolveJsonModule”: true, }, “include”: [“src//”, “global.d.ts”] } Troubleshooting Common Issues

Even with proper configuration, you might still encounter the “Cannot Find Module” error. Here are some common issues and their solutions.

  • Incorrect File Paths: Double-check the file paths in your import statements. Ensure that the paths are relative to the current file and that the file names and extensions are correct.
  • Missing Dependencies: Make sure you have installed all the necessary dependencies, including CSS loaders and plugins for your build tool.
  • Cache Issues: Sometimes, cached files can cause issues. Try clearing your TypeScript cache and rebuilding your project.

Let’s explore these in more detail. Incorrect file paths are a frequent cause of import errors. A simple typo or an incorrect relative path can prevent TypeScript from locating the module. Always double-check your import statements to ensure they accurately reflect the location of your CSS/SCSS files relative to the importing file. Using absolute paths can sometimes help avoid ambiguity, but ensure your baseUrl is correctly configured to support this. For instance, if you are importing a CSS module from a component located in a different directory, make sure the relative path accurately reflects the directory structure.

Missing dependencies can also lead to the “Cannot Find Module” error. If you are using a build tool like Webpack or Parcel, you need to install the appropriate loaders and plugins to handle CSS/SCSS files. For example, if you are using Webpack, you might need to install style-loader, css-loader, and sass-loader to handle CSS and SCSS files. Make sure these dependencies are installed and configured correctly in your build configuration file. If you forget to install one of these dependencies, your build tool will not be able to process the CSS/SCSS files, and TypeScript will not be able to find the corresponding modules. According to npm trends, ensuring dependencies are up-to-date and correctly installed reduces build errors by 30% [npm trends].

Lastly, cache issues can sometimes interfere with module resolution. TypeScript caches compiled files to improve build times, but sometimes this cache can become outdated or corrupted. Clearing the TypeScript cache can resolve these issues. You can typically clear the cache by deleting the node_modules/.cache directory or by running the tsc --clean command. After clearing the cache, rebuild your project to ensure that TypeScript recompiles all the files and resolves the modules correctly. This can often resolve obscure import errors that are difficult to diagnose otherwise.

Example Scenario: Webpack Configuration

Let’s say you are using Webpack and encountering the “Cannot Find Module” error. Here’s how you can configure Webpack to handle CSS/SCSS modules:

  1. Install the necessary loaders: npm install --save-dev style-loader css-loader sass-loader sass
  2. Configure your webpack.config.js file:

javascript module.exports = { module: { rules: [ { test: /\.module\.s(a|c)ss$/, use: [ ‘style-loader’, { loader: ‘css-loader’, options: { modules: { localIdentName: ‘[name]__[local]___[hash:base64:5]’, }, importLoaders: 1, }, }, ‘sass-loader’, ], }, ], }, resolve: { extensions: [’.scss’, ‘.sass’, ‘.js’, ‘.ts’, ‘.tsx’], }, }; This configuration tells Webpack to use style-loader to inject the CSS into the DOM, css-loader to process the CSS files, and sass-loader to compile SCSS files to CSS. The modules option in css-loader enables CSS Modules, which allows you to import CSS class names as JavaScript variables. The resolve option tells Webpack to look for files with the specified extensions, including .scss and .sass.

Facing the “Cannot Find Module” error when importing CSS/SCSS modules in TypeScript? The most common solution involves creating a global.d.ts file with module declarations for CSS and SCSS files. This tells TypeScript how to interpret these file types. Here’s the code: declare module ".module.css" { const classes: { readonly [key: string]: string }; export default classes; } declare module ".module.scss" { const classes: { readonly [key: string]: string }; export default classes; }. Place this file in your project, ensure it’s included in your tsconfig.json, and rebuild your project to resolve the error.

FAQ: Common Questions and Answers

Why am I getting "Cannot Find Module" even after creating a `.d.ts` file?
Ensure the `.d.ts` file is included in your `tsconfig.json` under the `include` or `files` option. Also, verify that the file path in your import statement matches the actual file location.
What is `moduleResolution` in `tsconfig.json`?
The `moduleResolution` setting tells TypeScript how to resolve modules. Common values are `node` and `bundler`, depending on your project setup. `node` is suitable for Node.js-style module resolution, while `bundler` is designed for use with modern bundlers like Webpack or Parcel.
How do I clear the TypeScript cache?
You can clear the TypeScript cache by deleting the `node_modules/.cache` directory or by running the `tsc --clean` command. Alternatively, restarting your IDE can sometimes clear the cache as well.
By carefully reviewing your TypeScript configuration, ensuring proper dependency management, and understanding the role of type declaration files, you can overcome the "**Cannot Find Module**" error and streamline your development process. Remember, consistent updates to your project dependencies and a clear understanding of your build tool's configuration are essential for long-term project health. Addressing this error not only resolves immediate compilation issues but also enhances the overall maintainability and scalability of your TypeScript projects. This allows you to focus on building robust and stylish applications. Need more help with TypeScript and module resolution? [Check out our advanced TypeScript course](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c).

Question & Answer :
I’m trying to import a theme from a CSS module but TypeScript gives me a “Cannot Find Module” error and the theme isn’t applied on runtime. I think there’s something wrong with my Webpack config but I’m not sure where the problem is.

I’m using the following tools:

"typescript": "^2.0.3" "webpack": "2.1.0-beta.25" "webpack-dev-server": "^2.1.0-beta.9" "react": "^15.4.0-rc.4" "react-toolbox": "^1.2.3" "node-sass": "^3.10.1" "style-loader": "^0.13.1" "css-loader": "^0.25.0" "sass-loader": "^4.0.2" "sass-lint": "^1.9.1" "sasslint-webpack-plugin": "^1.0.4" 

Here is my webpack.config.js

var path = require('path'); var webpack = require('webpack'); var sassLintPlugin = require('sasslint-webpack-plugin'); module.exports = { entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/dev-server', './src/index.tsx', ], output: { path: path.resolve(__dirname, 'dist'), publicPath: 'http://localhost:8080/', filename: 'dist/bundle.js', }, devtool: 'source-map', resolve: { extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'], }, module: { rules: [{ test: /\.js$/, loader: 'source-map-loader', exclude: /node_modules/, enforce: 'pre', }, { test: /\.tsx?$/, loader: 'tslint-loader', exclude: /node_modules/, enforce: 'pre', }, { test: /\.tsx?$/, loaders: [ 'react-hot-loader/webpack', 'awesome-typescript-loader', ], exclude: /node_modules/, }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] }, { test: /\.css$/, loaders: ['style', 'css'] }], }, externals: { 'react': 'React', 'react-dom': 'ReactDOM' }, plugins: [ new sassLintPlugin({ glob: 'src/**/*.s?(a|c)ss', ignoreFiles: ['src/normalize.scss'], failOnWarning: false, // Do it. }), new webpack.HotModuleReplacementPlugin(), ], devServer: { contentBase: './' }, }; 

and my App.tsx where I’m trying to import:

import * as React from 'react'; import { AppBar } from 'react-toolbox'; import appBarTheme from 'react-toolbox/components/app_bar/theme.scss' // local ./theme.scss stylesheets aren't found either interface IAppStateProps { // No props yet } interface IAppDispatchProps { // No state yet } class App extends React.Component<IAppStateProps & IAppDispatchProps, any> { constructor(props: IAppStateProps & IAppDispatchProps) { super(props); } public render() { return ( <div className='wrapper'> <AppBar title='My App Bar' theme={appBarTheme}> </AppBar> </div> ); } } export default App; 

What else is required to enable typesafe stylesheet module importing?

TypeScript does not know that there are files other than .ts or .tsx so it will throw an error if an import has an unknown file suffix.

If you have a webpack config that allows you to import other types of files, you have to tell the TypeScript compiler that these files exist. To do so add a declaration file in which you declare modules with fitting names.

The content of the module to declare depends on the webpack loader used for the file type. In a webpack configuration that pipes *.scss files through sass-loadercss-loaderstyle-loader, there will be no content in the imported module, and the correct module declaration would look like this:

// declaration.d.ts declare module '*.scss'; 

If the loaders are configured for css-modules just extend the declaration like this:

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