MyApp
├── main.js
└── modules
├── a.js
├── b.js
├── c.js
├── d.js
├── e.js
In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?
I have long list of modules and I dont want to import them all separately.
It implies the file name of the current module. It refers to the directory name of the current module. Note that every file in Node. js will wrap every file that it executes.
Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.
Create an index.js
in the modules/
folder:
const a = require('./a')
const b = require('./b')
const c = require('./c')
const d = require('./d')
const e = require('./e')
module.exports = {
a,
b,
c,
d,
e
}
Then just import the module in main.js
:
const modules = require('./modules')
modules.a
Alternatively you could loop through the directory and dynamically import each module.
You can dynamically import each module.
const fs = require('fs');
fs
.readdirSync(`${__dirname}/modules`)
.filter(file => (file.slice(-3) === '.js'))
.forEach((file) => {
require(`./modules/${file}`)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With