Import CSS Modules with TypeScript and webpack

Artem Sapegin
InstructorArtem Sapegin
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

If you try to use CSS Modules in TypeScript the same way you would use them in JavaScript, with webpack’s css-loader, you’ll see an error: ”TS2307: Cannot find module './styles.css'”. typings-for-css-modules-loader is a drop-in replacement for css-loader that works with TypeScript and generates typings for CSS on the fly.

You’ll need to install dependencies first:

npm install --save-dev css-loader typings-for-css-modules-loader

Instructor: [00:00] Using drop typings-for-css-modules-loader in your webpack config the same way as css-loader. You should keep all css-loader options like modules, but instead of css-loader, you should use typings-for-css-modules-loader. NamedExport option will generate typings as namedExport, which are more convenient, and camelCase option will convert class names with dashes to camelCase.

[00:23] Let's use this css file as an example. Note that the class name is in kebab-case, it contains a dash. Let's enter this file to our application. It's OK if you see you cannot find module error.

[00:35] Typings-for-css-modules-loader will generate typings file as soon as we start using styles. Apply our class name to a button. Note that now we're using camelCase class name. With dashes, we would have to use bracket notation, because JavaScript doesn't allow dashes and identifiers.

egghead
egghead
~ 21 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today