How to import all modules from a directory in TypeScript?

Typescript

Typescript Problem Overview


In TypeScript handbook few techniques for importing modules are described:

  • Import a single export from a module: import { ZipCodeValidator } from "./ZipCodeValidator";
  • Import a single export from a module and rename it: import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
  • Import entire module: import * as validator from "./ZipCodeValidator";

I expect there's one more option but nowhere I can find it. Is it possible to import all modules from a given directory?

I guess the syntax should be more or less like this: import * from "./Converters".

Typescript Solutions


Solution 1 - Typescript

No this is not possible. What most people do is create an index.js file which re-exports all files in the same directory.

Example:

my-module/
  a.ts
  b.ts
  index.ts

a.ts

export default function hello() {
  console.log("hello");
}

b.ts

export default function world() {
  console.log("world");
}

index.ts

export { default as A } from "./a";
export { default as B } from "./b";

You can use the * character to re-export every export of a module with a single line. Be aware that TypeScript will error if a member with the same name has already been exported though (thanks to @haysclark for the tip).

export * from "./somePath";

The index name can be dropped (same as in javascript):

import * as whatever from "./my-module";

console.log(whatever);
// Logs: { A: [Function: hello], B: [Function: world] }

Solution 2 - Typescript

I'm not sure if it safe to do for production code, but I use the following to import test code within a directory

import glob from 'glob'

new Promise((resolve, reject) => {
  glob(__dirname + '/**/*.ts', function (err, res) {
    if (err) {
      reject(err)
    } else {
      Promise.all(
        res.map(file => {
          return import(file.replace(__dirname, '.').replace('.ts', ''))
        })
      ).then(modules => {
        resolve(modules)
      })
    }
  })
}).then(modules => {
  // do stuff
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArkadiusz KałkusView Question on Stackoverflow
Solution 1 - TypescriptmarvinhagemeisterView Answer on Stackoverflow
Solution 2 - TypescriptTom HowardView Answer on Stackoverflow