Search code examples
javascripttypescriptweb-componentlit-element

Importing a module in typescript which does't exist yet, but will be present in the build directory


I have typescript module and a sass file for a component which exist in one directory. The typescript file will be transpiled at some path in the build directory and sass file will also be compiled to css file at same path in the build directory. Now I want to import css string from the compiled file which exist in the build directory. But while importing it in typescript its giving error that file doesn't exist. Now that is true that css file from which I'm trying to import doesn't exist yet, but it will be present relative to the compiled javascript file in the build directory. How to resolve this issue?

In typescript file I'm importing like this

import navbarStyles from './navbar.css';

The directory structure is

- /navbar
| - navbar.ts
| - navbar.scss

Expected result: I should be able to import string from css file as expected.


Solution

  • You can use wildcard module declaration. Putting something like the following in a css-modules.d.ts file (name doesn't matter) anywhere (usually in root) would work.

    declare module "*.css" {
        const path: string;
        export default path;
        // anything else that the bundler exports
    }
    

    If you are also bundling scss using webpack or something like that, import "./navbar.scss" would also work.