Skip to content

Webpack loader to create TypeScript declarations for CSS Modules

License

bhollis/css-modules-typescript-loader

 
 

Repository files navigation

npm semantic-release

@bhollis/css-modules-typescript-loader

Webpack loader to create TypeScript declarations for CSS Modules.

Emits TypeScript declaration files matching your CSS Modules in the same location as your source files, e.g. src/Component.css will generate src/Component.css.d.ts.

This is a fork of css-modules-typescript-loader with updates to keep up with newer features in css-loader.

Why?

There are currently a lot of solutions to this problem. However, this package differs in the following ways:

  • Encourages generated TypeScript declarations to be checked into source control, which allows webpack and tsc commands to be run in parallel in CI.

  • Ensures committed TypeScript declarations are in sync with the code that generated them via the verify mode.

Usage

Place @bhollis/css-modules-typescript-loader directly after css-loader in your webpack config.

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            '@bhollis/css-modules-typescript-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              namedExport: true,
            }
          }
        ]
      }
    ]
  }
};

Verify Mode

Since the TypeScript declarations are generated by webpack, they may potentially be out of date by the time you run tsc. To ensure your types are up to date, you can run the loader in verify mode, which is particularly useful in CI.

For example:

{
  loader: '@bhollis/css-modules-typescript-loader',
  options: {
    mode: process.env.CI ? 'verify' : 'emit'
  }
}

Instead of emitting new TypeScript declarations, this will throw an error if a generated declaration doesn't match the committed one. This allows tsc and webpack to run in parallel in CI, if desired.

This workflow is similar to using the Prettier --list-different option.

Named Exports

If you have disabled the namedExport option of css-loader then you can disable the same option in this loader.

{
  loader: '@bhollis/css-modules-typescript-loader',
  options: {
    namedExport: false,
  }
},
{
  loader: 'css-loader',
  options: {
    modules: true,
    namedExport: false,
  }
}

With Thanks

License

MIT.

About

Webpack loader to create TypeScript declarations for CSS Modules

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 93.2%
  • CSS 6.8%