Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import modules from all files in a directory, using a wildcard?

With ES6, I can import several exports from a file like this:

import {ThingA, ThingB, ThingC} from 'lib/things'; 

However, I like the organization of having one module per file. I end up with imports like this:

import ThingA from 'lib/things/ThingA'; import ThingB from 'lib/things/ThingB'; import ThingC from 'lib/things/ThingC'; 

I would love to be able to do this:

import {ThingA, ThingB, ThingC} from 'lib/things/*'; 

or something similar, with the understood convention that each file contains one default export, and each module is named the same as its file.

Is this possible?

like image 807
Joe Frambach Avatar asked Apr 18 '15 20:04

Joe Frambach


People also ask

How do I import a module dynamically?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);

How do I import a directory into TypeScript?

To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .


1 Answers

I don't think this is possible, but afaik the resolution of module names is up to module loaders so there might a loader implementation that does support this.

Until then, you could use an intermediate "module file" at lib/things/index.js that just contains

export * from 'ThingA'; export * from 'ThingB'; export * from 'ThingC'; 

and it would allow you to do

import {ThingA, ThingB, ThingC} from 'lib/things'; 
like image 100
Bergi Avatar answered Sep 20 '22 11:09

Bergi