Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import all modules from a directory at once [NODE]

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.

like image 470
Aditya Avatar asked Jul 08 '17 14:07

Aditya


People also ask

Does the node wrap all the modules?

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.

Can we export multiple classes from a component?

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.


2 Answers

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.

like image 74
Francisco Mateo Avatar answered Oct 19 '22 20:10

Francisco Mateo


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}`)
  });
like image 41
Anthony Ngene Avatar answered Oct 19 '22 20:10

Anthony Ngene