Autoplay

    Import CSS Modules with TypeScript and webpack

    Artem SapeginArtem Sapegin

    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
    webpackwebpack
    typescriptTypeScript
    cssCSS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss