[英]What is the syntax to export a function from a module in Node.js?
从Node.js中的模块导出函数的语法是什么?
function foo() {}
function bar() {}
export foo; // I don't think this is valid?
export default bar;
在Node中,您可以使用module.exports
特殊对象导出内容。 例如:
这导出了两个函数:
module.exports = { foo, bar };
它们可以用作:
const { foo, bar } = require('./module/path');
要将其中一个函数导出为顶级对象,您可以使用:
module.exports = foo;
module.exports.bar = bar;
可以用作:
const foo = require('./module/path');
和:
const { bar } = require('./module/path');
要么:
const foo = require('./module/path');
const { bar } = foo;
要么:
const foo = require('./module/path');
const bar = foo.bar;
等等
这是“从Node.js中的模块导出函数的语法”,如问题中所要求的 - 即Node本身支持的语法。 Node不支持import
/ export
语法(请参阅此内容以了解原因)。 正如slezica在下面的评论中指出的那样,您可以使用像Babel这样的转换器将import
/ export
关键字转换为Node理解的语法。
有关详细信息,请参阅这些答案
公开foo和bar函数:
module.exports = {
foo: function() {},
bar: function() {}
}
您也可以采用较短的形式
// people.js
function Foo() {
// ...
}
function Bar() {
// ...
}
module.exports = { Foo, Bar}
输入:
// index.js
const { Foo, Bar } = require('./people.js');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.