[英]What is the syntax to export a function from a module in Node.js?
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;
In Node you export things with module.exports
special object. 在Node中,您可以使用
module.exports
特殊对象导出内容。 For example: 例如:
This exports both functions: 这导出了两个函数:
module.exports = { foo, bar };
They can be used as: 它们可以用作:
const { foo, bar } = require('./module/path');
To export one of those functions as top-level object you can use: 要将其中一个函数导出为顶级对象,您可以使用:
module.exports = foo;
module.exports.bar = bar;
which can be used as: 可以用作:
const foo = require('./module/path');
and: 和:
const { bar } = require('./module/path');
or: 要么:
const foo = require('./module/path');
const { bar } = foo;
or: 要么:
const foo = require('./module/path');
const bar = foo.bar;
etc. 等等
This is "the syntax to export a function from a module in Node.js" as asked in the question - ie the syntax that is natively supported by Node. 这是“从Node.js中的模块导出函数的语法”,如问题中所要求的 - 即Node本身支持的语法。 Node doesn't support
import
/ export
syntax (see this to know why). Node不支持
import
/ export
语法(请参阅此内容以了解原因)。 As slezica pointed put in the comments below you can use a transpiler like Babel to convert the import
/ export
keywords to syntax understood by Node. 正如slezica在下面的评论中指出的那样,您可以使用像Babel这样的转换器将
import
/ export
关键字转换为Node理解的语法。
See those answers for more info: 有关详细信息,请参阅这些答案
to expose both foo and bar functions: 公开foo和bar函数:
module.exports = {
foo: function() {},
bar: function() {}
}
You can also do this in a shorter form 您也可以采用较短的形式
// people.js
function Foo() {
// ...
}
function Bar() {
// ...
}
module.exports = { Foo, Bar}
Importing: 输入:
// index.js
const { Foo, Bar } = require('./people.js');
export function foo(){...};
Or, if the function has been declared earlier: 或者,如果之前声明了该函数:
export {foo};
Reference: MDN export 参考: MDN导出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.