How to use CSS Modules with TypeScript and webpack

import s from './Button.css';

The easy way

You can bypass TypeScript import magic by using require instead of import:

const s = require('./Button.css');

The better way

To use import you need typings for CSS. For example, you have Button.css like this:

.foo {
color: chocolate;
}
.barBaz {
color: tomato;
}
export const foo: string;
export const barBaz: string;
npm install --save-dev typings-for-css-modules-loader
module: {
rules: [
{
test: /\.css$/,
include: path.join(__dirname, 'src/components'),
use: [
'style-loader',
{
loader: 'typings-for-css-modules-loader',
options: {
modules: true,
namedExport: true
}
}
]
}
]
}
import * as s from './Button.css';

--

--

Frontend developer, passionate photographer and owner of crazy dogs. Creator of React Styleguidist.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Artem Sapegin

Artem Sapegin

Frontend developer, passionate photographer and owner of crazy dogs. Creator of React Styleguidist.