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.
From TypeScript v2.4 you can use dynamic import to achieve conditional importing
An async example:
async function importModule(moduleName: string):Promise<any>{ console.log("importing ", moduleName); const importedModule = await import(moduleName); console.log("\timported ..."); return importedModule; } let moduleName:string = "module-a"; let importedModule = await importModule(moduleName); console.log("importedModule", importedModule);
I have a slightly clunky but very effective solution for this, particularly if you're using conditional import/export for unit testing.
Have an export that is always emitted, but make the contents vary based on a runtime value. E.g.:
// outputModule.ts export const priv = (process.env.BUILD_MODE === 'test') ? { hydrateRecords, fillBlanks, extractHeaders } : null
Then in the consuming file, import the export, check that the imported value exists, and if it does, assign all the values you'd otherwise import stand-alone to a set of variables:
// importingModule.spec.ts import { priv } from './outputModule'; const { hydrateRecords, fillBlanks, extractHeaders } = priv as any; // these will exist if environment var BUILD_MODE==='test'
Limitations:
Still, it worked really well for me for my purposes, hopefully it works for you too. It's particularly useful for unit testing private methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With