TypeScript – conditional module import/export


TypeScripts abstracts away module imports/exports in sort of ‘declarative’ manner.

But what if I want to import or export something based on some runtime-computed condition?

The most common use case is sharing code between platforms like Node.js and Windows Script Host.

TypeScript’s very own io.ts that abstracts input/output in TSC compiler manually hacks around the built-in TypeScript’s very own module syntax. Is that the only way?

P.S. The problem with just sticking import fs = module(“fs”) into if statement is that TypeScript only allows import statements at a top level. Which means in WSH require(“fs”) will be executed and obviously failing, as require is undefined.


I agree that the fact that they can only have toplevel scope is suboptimal at best. Besides the issue you stated, it also means slower initial load times of software. For example within nodejs I now sometimes load a module in a function if that function is seldom used. So my application starts up quicker since it doesn’t load that module yet.

And of course you could use require or AMD directly, but than you will miss some of the typing benefits.

I think however that the real problem lies in the fact that harmony/es6 defined modules to be toplevel and TS seems to be following that proposal. So not sure how much TS team can do without diverging from the standards.

Answered By – JBaron

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published