Home >Web Front-end >JS Tutorial >How to Import All Modules from a Directory in JavaScript?
Importing Modules from All Files in a Directory Using a Wildcard
When working with ES6, it's possible to import multiple exports from a single file using the following syntax:
import {ThingA, ThingB, ThingC} from 'lib/things';
However, for organizational purposes, it may be preferable to have one module per file. This leads to imports resembling the following:
import ThingA from 'lib/things/ThingA'; import ThingB from 'lib/things/ThingB'; import ThingC from 'lib/things/ThingC';
An ideal scenario would be to import modules from all files in a directory using a wildcard, like so:
import {ThingA, ThingB, ThingC} from 'lib/things/*';
This would adhere to the convention of having each file contain a single default export and naming it the same as its file.
Feasibility of Wildcards
Unfortunately, importing modules using wildcards is currently not supported in JavaScript. Module name resolution is handled by module loaders, and there might be specific implementations that do support this functionality.
Alternative Solution
In the absence of wildcard support, you can create an intermediate "module file" at lib/things/index.js containing the following:
export * from 'ThingA'; export * from 'ThingB'; export * from 'ThingC';
This allows you to import the desired modules using a single statement:
import {ThingA, ThingB, ThingC} from 'lib/things';
The above is the detailed content of How to Import All Modules from a Directory in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!