![](/img/trans.png)
[英]Does experimental ES Module loading in NodeJS support importing named exports?
[英]Importing all exports in a module NodeJS
我希望能够访问模块的所有导出,而不必说module.
出口前。
假设我有一个模块:
// mymod.js
module.exports.foo = function() {
console.log("foo!");
}
module.exports.bar = "bar!";
和一个主文件:
// main.js
var mymod = require("./mymod.js");
mymod.foo();
有没有办法调用foo()
而无需说mymod.
前? 这可以在 python 中通过import module as *
来实现。 与此等效的 NodeJS 是什么?
在 ES6 中,您可以通过以下方式导入模块
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
这些是 ES6 提供的唯一导入模块的方法(您也可以使用require
)。
如果您必须导入 100 多个模块,最好的方法是第一种方法,将所有内容作为对象导入并在旅途中解构,我的意思是如果您有很多函数或方法,请在该函数中解构您想要的函数,例如。
import * as moduleName from "path/to/file";
function function1(){
const { exportMember1, exportMember2 } = module;
}
function function2(){
const { exportMember1, exportMember5, exportMember7 } = module;
}
我希望能够访问模块的所有导出,而不必说 module。 出口前。
使用简写:
exports.myVar = myVar
exports.foo = () => {}
或者使用一个对象:
module.exports = {
foo,
myVar
}
// main.js
var mymod = require("./mymod.js");
mymod.foo();
有没有办法调用 foo() 而无需说 mymod. 前? 这可以在 python 中通过将 import module 声明为 * 来实现。 与此等效的 NodeJS 是什么?
使用解构:
const { foo } = require("./mymod.js")
假设我在一个文件中有 100 个导出。 我是否需要在每次导入后在 { } 中添加逗号? 必须有更好的方法来做到这一点
如果您有 100 个导出,为什么要将它们作为自己的函数全局导入? 为了清楚起见, myMod.func
更好。
一个hacky解决方法可能是做const myMod = require('myMod')
然后将其映射到全局对象上。 或者从一开始就将它们放在全局上而不是导出它。
您可以使用 ES6 解构:
var { foo } = require("./mymod.js");
foo();
我有一种情况,我有一个很小但不是那么小的通用实用程序,它与几个模块一起使用(使用了所有它的功能),其中已经加载了相当数量的模块。 这个函数的命名方式显然是你知道通用实用程序模块的一部分,所以“module.function”是多余的,不会提高代码的可读性。 所以,我更喜欢模仿 Python 的“import * from module”。 请注意,这是我第一次遇到这种情况,因此,IMO,这种机制几乎在所有情况下都不是一个好的做法。 唯一的方法是迭代模块的导出,并将函数添加到全局对象。 我做了一个功能来明确意图。
const importAll = () => {
return {
mod: null,
from(modName) {
this.mod = require(modName);
Object.keys(this.mod)
.forEach(exportedElementId => global[exportedElementId] = this.mod[exportedElementId]);
}
}
}
它是这样使用的:
importAll().from('module-name');
请注意,这仅在模块导出对象时才有效。 例如,如果模块导出数组,则无法工作。
这是另一种方法,它可能更方便一些(当然对我来说):
考虑你有你的模块:
// 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 };
然后在您的应用程序中,您可以按如下方式解包您的模块:
// app.js
require('./module.js').importAll();
console.log("func1() =", func1());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.