CSS Modules TypeScript Loader

4.0.1 · maintenance · verified Sun Apr 19

css-modules-typescript-loader is a Webpack loader designed to generate TypeScript declaration files (.d.ts) for CSS Modules. This enables developers to achieve type-safe access to CSS class names within their TypeScript projects, preventing runtime errors due to mistyped or non-existent class references. The current stable version, 4.0.1, was released in September 2020. While lacking a rigid release schedule, previous major updates occurred roughly annually. A key differentiator of this loader is its emphasis on checking the generated TypeScript declarations into source control. This approach facilitates parallel execution of `webpack` and `tsc` commands in Continuous Integration (CI) pipelines, optimizing build times. Furthermore, it offers a unique `verify` mode, which, when enabled, ensures that the committed TypeScript declarations remain in sync with the dynamically generated types, providing an additional layer of consistency assurance.

Common errors

Warnings

Install

Imports

Quickstart

This Webpack configuration demonstrates how to integrate `css-modules-typescript-loader` to generate TypeScript declaration files for CSS Modules, ensuring type safety for CSS class names within a TypeScript project.

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.css']
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'css-loader',
            options: {
              modules: true, // Enable CSS Modules
              importLoaders: 1 // Number of loaders applied before CSS loader
            }
          },
          // This loader MUST come directly after css-loader
          {
            loader: 'css-modules-typescript-loader',
            options: {
              // Use 'verify' in CI to ensure types are up-to-date
              mode: process.env.CI ? 'verify' : 'emit'
            }
          }
        ]
      }
    ]
  },
  devtool: 'source-map'
};

view raw JSON →