K
K
kr_ilya2020-05-02 12:11:12
Node.js
kr_ilya, 2020-05-02 12:11:12

Is it smart to import the same libraries in every module?

If I need the same libraries in different modules, I do this:
a.js

const os = require('os'),
  path = require('path'),
  fs = require('fs'),
  kb = require('./modules/keyboards.js'),
  config = require('./config.js');

var state = {};

require('./modules/b')(state);

...


b.js
const os = require('os'),
  path = require('path'),
  fs = require('fs'),
  kb = require('../modules/keyboards.js'),
  config = require('../config.js');

module.exports = (state) => {

...
}


Is it right to do so at all? How does this affect performance? How to do it better?
I believe that it is possible to pass all modules directly to a function (as is done with state), but I don't want to clutter up the arguments.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-05-02
@kr_ilya

In each module, import everything and only what is needed for this module to work directly. So your system will be more flexible and it will be easier to work with each module separately. Modules are designed to be imported only once, no matter how many times you call require.
Your approach is quite normal, unless of course you import into module A something that is used only in module B and not used in module A directly. I would not
move all imports into a separate file, as Dmitry suggests.
BUT

pass all modules directly to the function (as it is done with state)
justified only if you implement the Strategy pattern

D
Dmitry, 2020-05-02
@dimoff66

Then just collect them all in one file into an object and import the object, why is it so difficult?

const os = require('os'),
  path = require('path'),
  fs = require('fs'),
  kb = require('../modules/keyboards.js'),
  config = require('../config.js');

module.exports = { os, path, fs, kb, config }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question