所以我正在构建一个数据库层,并将您的标准 CRUD(创建、读取、更新、删除)操作公开为函数。我正在研究以何种方式导出每个函数。
方法一
function func1 () {}
function func2 () {}
module.exports = {
"func1": func1,
"func2": func2
}
方法二
var exporting;
exporting.func1 = function() {};
exporting.func2 = function() {};
module.exports = exporting;
或者,直接执行:
module.exports.func1 = function() {};
module.exports.func2 = function() {};
方法三
export func1 = function() {}
export func2 = function() {}
我确信它不会破坏任何方法,但每种方法的优缺点(如果有的话)是什么?
最佳答案
根据您的示例,示例#1 和#2 是同一件事,因为 exports
是一个对象。您只是在更改向该对象添加条目的方式。
这个:
const object = {};
object.func1 = function () { return 'hello'; };
object.func2 = function () { return 'bye'; };
你可以这样写:
const object = {
func1: function () { return 'hello'; },
func2: function () { return 'bye'; }
};
最后一个例子拥有ES2015 modules并且尚未在 V8 中实现(Node.js 在其中运行)。对于此示例,您需要软件包 babel和 babel-preset-es2015 .
但是,使用 CommonJS 和 ES2015 模块之间有一个重要的区别:
CommonJS modules export values, while ES6 modules export immutable bindings. That means: CommonJS export a copy of the module while ES2015 modules export a reference of it.
关于javascript - 在 Node 中导出各种功能的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41253462/