Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - conditional module import/export

Tags:

typescript

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.

like image 292
Oleg Mihailik Avatar asked Nov 18 '12 20:11

Oleg Mihailik


2 Answers

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); 
like image 85
mPrinC Avatar answered Sep 23 '22 09:09

mPrinC


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:

  1. You sadly have to set the import to 'any' to make the compiler happy.
  2. You need to check for whether or not specific imports are defined (but that comes with the territory).
  3. The importing file will expect the values to be defined. You will thus have to ensure importing files actually need the modules (which is fine if you're e.g. dealing with files only run during testing), or you'll have to define alternative values for cases where they don't actually get exported.

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.

like image 32
Andrew Faulkner Avatar answered Sep 21 '22 09:09

Andrew Faulkner