Is it possible to import modules from all files in a directory, using a wildcard?
In JavaScript, wildcard imports aren't directly supported by ES6 import
syntax. To import all modules from a directory, Node.js fs
and path
modules are used with import()
:
This approach enables dynamic, at runtime, loading of modules by reading the directory content and importing each file individually, returning a Promise for all these module imports.
Implement the index.js strategy
Let's use an index.js
file for grouping up our exports:
That way you offer a single-point import, thus cleaning your code from various import lines.
Empowering Babel with wildcards
For Babel users, the babel-plugin-wildcard
plugin allows Nature documentary levels of wildcard imports.
-
Install the plugin:
// New plugin, who dis?
-
Configure it in your
.babelrc
:
Afterwards, you're all set for some wild imports:
Harness dynamic imports' potential
The dynamic import()
function lets you import modules on the go:
await import()
offers a cleaner and shorter code:
Embrace the power of ES6 syntax
With ES6 you can use spread syntax and named exports to keep your modules clean and tidy:
This maintains your modules as separate, clear entities, leading to easier management on the import side.
Be aware when going global
Globals can free you from imports and exports if you use index.js
:
But remember, with great power comes great responsibility. Avoid potential namespace pollution.
Webpack's context to the rescue
Webpack's require.context()
provides another way to import multiple files:
Was this article helpful?