7

How can I run scripts that import css modules?

I'm writing a typescript migration script that I'd like to run via ts-node. Ideally, my codebase would be organized such that the script's dependencies never touch React components, but that's not the case. The script ultimately imports React components and thus css modules, so ts-node fails because it doesn't understand css modules:

RenderableInline.tsx(4,20): error TS2307: Cannot find module './styles/RenderableInline.module.scss' or its corresponding type declarations.

Only webpack understands how to build css modules, since I've configured it via a css-loader.

The only precedent for this I've found is jest, which has some configuration option for mocking out css modules so it can import these files without error: https://jestjs.io/docs/webpack.

How can I run a typescript script that has dependencies on css modules? Is there someway to do this via ts-node? Or does webpack have some script running feature?

Michael Gummelt
  • 702
  • 4
  • 15

1 Answers1

0

Add a global .d.ts file that provides direction on how .css files should be handled.

Such as src/global.d.ts with the following contents:

declare module '*.module.css' {
  const classes: { [key: string]: string };
  export default classes;
}

May also be helpful to add the typescript-plugin-css-modules plugin. Note though that this only helps during development using VSCode but has no effect during compilation.


While I generally got this working, I am still facing problems to get this to work correctly with ts-node-dev - probably related to ts-node not loading these type files by default Missing Types. Unfortunately even using the --files directive, I couldn't get this to work.

mxro
  • 6,588
  • 4
  • 35
  • 38