[软件设计/软件工程] 在 Node.js 中声明多个 module.exports

[复制链接]
发表于 2022-5-6 13:40:40
问题
我想要实现的是创建一个包含多个功能的模块。

模块.js:
  1. module.exports = function(firstParam) { console.log("You did it"); },
  2. module.exports = function(secondParam) { console.log("Yes you did it"); },
  3. // This may contain more functions
复制代码

主.js:
  1. var foo = require('module.js')(firstParam);
  2. var bar = require('module.js')(secondParam);
复制代码

我遇到的问题是 firstParam 是一个对象类型,而 secondParam 是一个 URL 字符串,但是当我遇到这个时,它总是抱怨错误的类型。

在这种情况下,如何声明多个 module.exports?

回答
你可以这样做:
  1. module.exports = {
  2.     method: function() {},
  3.     otherMethod: function() {},
  4. };
复制代码

要不就:
  1. exports.method = function() {};
  2. exports.otherMethod = function() {};
复制代码

然后在调用脚本中:
  1. const myModule = require('./myModule.js');
  2. const method = myModule.method;
  3. const otherMethod = myModule.otherMethod;
复制代码






上一篇:如何在 Swift 中停止(或暂停)设备的音频?
下一篇:Three.js 对象返回错误位置/旋转/缩放值

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表