我试图实现的是创建一个包含多个功能的模块。

module.js:

module.exports = function(firstParam) { console.log("You did it"); },
module.exports = function(secondParam) { console.log("Yes you did it"); }, 
// This may contain more functions

main.js:

var foo = require('module.js')(firstParam);
var bar = require('module.js')(secondParam);

我的问题是,firstParam是一个对象类型和secondParam是一个URL字符串,但当我有它总是抱怨类型是错误的。

我如何声明多个模块。在这种情况下出口?


当前回答

你可以像我下面做的那样…对于函数和箭头函数:

greet.js:

函数greetFromGreet() { Console.log ("hello from greet module…"); } const greetVar = () => { Console.log("将var视为箭头fn/…"); }; 模块。exports = {greetVar, greetFromGreet};// ----多个模块导出…

// -----------------------------------------------

app.js:

const greetFromGreets = require("./greet");

greetFromGreets.greetFromGreet();
greetFromGreets.greetVar();

// -----------------------------------------------

其他回答

在你的节点模块中,你可以导出各种函数,比如:

Module.exports.eat =吃; 函数eat() { …… 返回* *的东西; }; Module.exports.sleep =睡眠; 函数sleep() { …… 返回* *的东西; };

注意,导出函数时并没有调用它们。 然后,在要求模块时,您可以要求为:-

Const task = require(__dirname + "/task.js"); //task是文件的名称 Let eat = task.eat(); Let sleep = task.sleep();

两种类型的模块导入和导出。

类型1 (module.js):

// module like a webpack config
const development = {
  // ...
};
const production = {
  // ...
};

// export multi
module.exports = [development, production];
// export single
// module.exports = development;

类型1 (main.js):

// import module like a webpack config
const { development, production } = require("./path/to/module");

类型2 (module.js):

// module function no param
const module1 = () => {
  // ...
};
// module function with param
const module2 = (param1, param2) => {
  // ...
};

// export module
module.exports = {
  module1,
  module2
}

类型2 (main.js):

// import module function
const { module1, module2 } = require("./path/to/module");

如何使用导入模块?

const importModule = {
  ...development,
  // ...production,
  // ...module1,
  ...module2("param1", "param2"),
};

这只是供我参考,因为我想要达到的目的可以通过这个来实现。

在module.js中

我们可以这样做

    module.exports = function ( firstArg, secondArg ) {

    function firstFunction ( ) { ... }

    function secondFunction ( ) { ... }

    function thirdFunction ( ) { ... }

      return { firstFunction: firstFunction, secondFunction: secondFunction,
 thirdFunction: thirdFunction };

    }

在main.js中

var name = require('module')(firstArg, secondArg);

你可以写一个函数来手动委托其他函数:

module.exports = function(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};

如果文件是用ES6导出的,你可以写:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};