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

Frambot picture Frambot · Apr 18, 2015 · Viewed 234.8k times · Source

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?

Answer

Bergi picture Bergi · Apr 18, 2015

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';