减少模块重复输出功能?

时间:2018-12-04 06:14:24

标签: javascript node.js npm ecmascript-6

我在index.js中有2个功能

module.exports.func1 = func1
module.exports.func2 = func2

然后在我需要这样的地方

const func1 = require('./index').func1
const func2 = require('./index').func2

反正还有“清理”吗?如果我有更多功能怎么办,那会很混乱。

6 个答案:

答案 0 :(得分:4)

由于module.exports是一个对象,并且由于require()返回了该对象,因此您可以对该对象进行解构:

const { func1, func2 } = require('./index');

如果您需要将属性提取到属性名称之外的其他变量名中,则可以遵循通常的销毁规则在销毁时重命名:

const { func1, func2: myFunc2 } = require('./index');
// use "func1" and "myFunc2" here

答案 1 :(得分:1)

您可以在index.js中执行以下操作:

var func = {
   func1 : func1,
   func2 : func2
};
module.exports = func;

然后要求使用解构:

const {func1} = require('./index');
const {func2} = require('./index');

或单个衬里

const { func1, func2 } = require('./index');

答案 2 :(得分:0)

您可以使用大括号破坏对象。

const { func1, func2 } = require('./index')

或者您可以使用类或对象,而func1,func2将是该类或对象中的方法或属性

function MyFunc () {
   this.func1 = function () {}
   this.func2 = function () {}
}

module.exports = new MyFunc()

var myFunc = {
   func1: function () {}
   func2: function () {}
}
module.exports = myFunc

然后您以类似方式导入

const myFunc = require("./index")
const func1 = myFunc.func1()

答案 3 :(得分:0)

对于导出功能,您可以在 index.js 中导出功能,如下所示:

module.exports = {
  func1: func1_def,
  func2: func2_def
};

func1_def func2_def 是函数定义。 您可以按照以下说明导入这些功能并直接使用。

const { func1, func2 } = require('./index');

答案 4 :(得分:0)

要更简单地执行导出,您可以执行以下操作:

module.exports = { func1, func2 }

要更简洁地满足需求,您可以执行以下操作:

const { func1, func2 } = require('./index')

答案 5 :(得分:0)

您可以像这样导出所有方法:

module.exports = {
  func1: () => {
    // logic
  },
  func2: () => {
    // logic
  },
}

然后您可以像下面这样使用

// import or require
const myMethods = require('./path/filename');

// call the method
myMethods.insertUser();
myMethods.loginAction();
myMethods.checkDuplicationID();
相关问题