简体   繁体   中英

Importing all exports in a module NodeJS

I want to be able to access all exports of a module without having to say module. before the export.

Let's say that I have a module:

// mymod.js
module.exports.foo = function() {
    console.log("foo!");
}
module.exports.bar = "bar!";

And a main file:

// main.js
var mymod = require("./mymod.js");
mymod.foo();

Is there a way to call foo() without needing to say mymod. before? This can be achieved in python by saying import module as * . What is the NodeJS equivalent to this?

In ES6 you can import modules in the following ways

import moduleName from "path/to/module"; // import default export from the file as moduleName object, moduleName can be anything
import { exportMemberName1, exportMemberName2, ... } from "path/to/module"; // destructured import, it will destructure import and can access the export module without prefixing anything
import * as moduleName from "path/to/module"; // import everything exported from the file as moduleName object, you can access every export members from that object, moduleName can be anything

These are the only methods provided by ES6 to import module (you can also use require ).

If you have to import 100s of modules best ways is first method, import everything as an object and destructure on the go, I meant if you have lots of functions or methods, destructure what you want in that function in side that function, eg.

import * as moduleName from "path/to/file";

function function1(){
    const { exportMember1, exportMember2 } = module;
}

function function2(){
    const { exportMember1, exportMember5, exportMember7 } = module;
}

I want to be able to access all exports of a module without having to say module. before the export.

Use the shorthand:

exports.myVar = myVar
exports.foo = () => {}

Or use an Object:

module.exports = {
  foo,
  myVar
}

// main.js
var mymod = require("./mymod.js");
mymod.foo();

Is there a way to call foo() without needing to say mymod. before? This can be achieved in python by saying import module as *. What is the NodeJS equivalent to this?

Use destructuring:

const { foo } = require("./mymod.js")

lets say that I have 100 exports in a file. Do I need to put commas after every import inside the { }? There must be a better way to do this

If you have 100 exports why would you want to import them all globally as their own functions? myMod.func is better for clarity.

A hacky workaround might be to do const myMod = require('myMod') then map it putting the functions on the global object. Or put them on the global from the start instead of exporting it.

You can use ES6 destructuring:

var { foo } = require("./mymod.js");
foo();

I have a situation where a I have a tiny-but-not-that-tiny generic utilities that is used along a couple of modules (all it's functions are used), in which there is a decent amount of modules already loaded. This functions are obviously named in a way you know there are a part of a generic utilities modules, so the "module.function" it's redundant, does not improve the readeability of the code. So, I prefered to mimick the "import * from module" of Python. Note that this is the first time I come across this situation, therefore, IMO, this mechanism, in almost every case, is not a good practice at all. The only way to do that, is iterating over the exports of the module, and adding the functions to the global object. I made a function to make the intention clear.

const importAll = () => {
  return {
    mod: null,
    from(modName) {
      this.mod = require(modName);
      Object.keys(this.mod)
            .forEach(exportedElementId => global[exportedElementId] = this.mod[exportedElementId]);
    }
  }
}

And it is used like this:

importAll().from('module-name');

Note that this only works if the module exports an object. Wont work if the module exports, for example, an array.

Here is another way, which may be a bit more convenient (it certainly is for me):

Consider you have your module:

// module.js

function func1() { return 1; };
function func2() { return 2; };
function importAll() { Object.keys(this).forEach((id) => { if (id === 'importAll') { return; }; global[id] = this[id]; }); };
module.exports = { func1, func2, importAll };

and then in your app you can unwrap your module as follows:

// app.js

require('./module.js').importAll();

console.log("func1() =", func1());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM