Joe Frambach Joe Frambach - 20 days ago 8
Javascript Question

import modules from files in directory

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

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