Search code examples
typescriptvisual-studio-code

How can I make TypeScript elide star/wildcard imports that are only supposed to be used in type contexts?


I'm using a library called turf.js. They do not offer a specific type definition file but instead suggest to install the node module and have typescript find the types as such:

import * as turf from '@turf/turf';

This works nicely while editing. All types are picked up.

In the generated .js file it looks like this.

import * as turf from '@turf/turf';

I don't want or need that in the .js file. If I leave it in there the browser will fail to load the file with an error. If I simply comment that line out, everything works as expected.

The turf file is getting loaded from a cdn via a normal script tag.

How do I tell VS Code / TypeScript that is just used for type hints?

I have tried finding options in tsconfig.json to exclude an import but didn't find anything.


Solution

  • The thing that weirds me out about what you're asking is that- to my understanding, as long as you don't touch any of the following options- verbatimModuleSyntax (introduced in v5.0), preserveValueImports, and importsNotUsedAsValues options- the import should be elided if you only use it in type contexts.

    That aside, you should be able to write import type * as foo from "path". Note that type-only imports are only supported since version 3.8 of TypeScript.

    If you actually use it as a value (and not just in type contexts), but still want the import to be elided, then either tweak something with your post-processing (Ex. build system / tree shaking things), or use/abuse triple-slash references.