'How to import CSS modules with Typescript, React and Webpack
How to import CSS modules in Typescript with Webpack?
Generate (or auto-generate)
.d.tsfiles for CSS? And use classic Typescriptimportstatement? With./styles.css.d.ts:import * as styles from './styles.css'Import using
requireWebpack function?let styles = require("./styles.css");
But for the last approach I must define the require function.
What is the best approach or best option and one that can also handle IntelliSense for the CSS file definitions and classes?
Solution 1:[1]
A) As you are saying, there is one simplest (not best) option to use require:
const css = require('./component.css')
- We need to have typings for
requireas it's not standard feature in typescript. Simplest typing for this specific require may be:
declare function require(name: string): string;Webpack will then compile typescript and use modules properly - BUT without any IDE help and class names checks for build.
B) There is better solution to use standard import:
import * as css from './component.css'
- enables full class names IntelliSense
- requires types definition for each css file, otherwise
tsccompiler will fail
For proper IntelliSense, Webpack needs to generate types definition for each css file:
Use webpack typings-for-css-modules-loader
webpackConfig.module.loaders: [ { test: /\.css$/, loader: 'typings-for-css-modules?modules' } { test: /\.scss$/, loader: 'typings-for-css-modules?modules&sass' } ];Loader will generate
*.css.d.tsfiles for each of css files in your codebase- Typescript compiler will understand that css import will be module with properties (class names) of type string.
Mentioned typings-for-css-loader contains a bug and because of types file generation delay, it's best to declare global *.css type in case our *.css.d.ts file is not generated yet.
That little bug scenario:
- Create css file
component.css - Include it in component
import * as css from './component.css' - Run
webpack - Typescript compiler will try to compile code (ERROR)
- Loader will generate Css modules typings file (
component.css.d.ts), but it's late for typescript compiler to find new typings file - Run
webpackagain will fix build error.
Easy fix is to create global definition (eg. file called typings.d.ts in your source root) for importing CSS Modules:
declare module '*.css' {
interface IClassNames {
[className: string]: string
}
const classNames: IClassNames;
export = classNames;
}
This definition will be used if there is no css file generated (eg. you have added new css file). Otherwise will be used generated specific (needs to be in same folder and named same as source file + .d.ts extension), eg. component.css.d.ts definition and IntelliSense will work perfectly.
Example of component.css.d.ts:
export const wrapper: string;
export const button: string;
export const link: string;
And if you don't want to see generated css typings you may setup filter in IDE to hide all files with extension .css.d.ts in your sources.
Solution 2:[2]
Now in the year 2021, all you need to do is add a src/Globals.d.ts to your project with these lines:
declare module "*.module.css";
declare module "*.module.scss";
// and so on for whatever flavor of css you're using
Then install and add
{
"compilerOptions": {
"plugins": [{ "name": "typescript-plugin-css-modules" }]
}
}
to your tsconfig.
Example of this correctly functioning in VS code after making that simple change (root is a class defined in my stylesheet):
Webpack and tsc also compile correctly on the command line.
Solution 3:[3]
I have added a file named Global.d.ts or typings.d.ts to my ./src folder with some type definitions:
declare module "*.module.css";
Webpack css config:
{
test: /\.css$/,
use: [
isProductionBuild ? MiniCssExtractPlugin.loader : "style-loader",
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
localIdentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true
}
}
]
},
Then I simply import the module like: import styles from "./App.module.css";
Solution 4:[4]
In 2022, all I needed to do it to add Globals.d.ts file under the src folder
with
declare module "*.module.css";
declare module "*.module.scss";
Then I can import CSS modules in my typescript files as usual for css or scss files:
import styles from "./Team.module.scss";
Solution 5:[5]
Or import using require webpack function
This is just what I used to do and still have that code in a few of my projects out there.
Now : I wrote typestyle : http://typestyle.github.io/#/ but you don't have to use it. Just stick with const styles = require('./styles.css') if it makes you happy. FWIW you can also use raw css with typestyle if you want http://typestyle.github.io/#/raw
Solution 6:[6]
I think now typescript can import css file by simply doing import 'fileTobeImportedPath.css'
Solution 7:[7]
This case is related to Typescript. You can add typings.d.ts in your project with this content:
declare module "*.module.css";
declare module "*.module.scss";
It is good practice to use file name with *.module.* format if you want to enable CSS Module.
css-loader will enable CSS Module automatically for files with name that satisfy this RegEx: /\.module\.\w+$/i. This feature is customable by setting options.modules property as an object.
For example:
import style from './App.module.css'; // CSS Module enabled
import './index.css'; // Plain CSS loaded
For recent configuration, you can add this rule to webpack.config.js:
{
test: /\.css$/,
use: [
'style-loader',
{
loader: "css-loader",
options: {
modules: {
localIdentName: "[hash:base64]", // default
auto: true // default
},
sourceMap: true
}
},
]
},
A custom configuration example:
{
loader: "css-loader",
options: {
modules: {
localIdentName: "[name]_[local]_[hash:base64]", // custom class name format
auto: /\.cmod\.\w+$/i, // custom auto enable CSS Module for "*.cmod.css" format
},
}
},
Complete documentation is HERE.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ulou |
| Solution 3 | |
| Solution 4 | Tal Haham |
| Solution 5 | |
| Solution 6 | Yingying |
| Solution 7 | Luki B. Subekti |

