Zadeklaruj wiele modułów module.exports w Node.js


243

Staram się stworzyć jeden moduł, który zawiera wiele funkcji.

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);

Problem, który mam, polega na tym, że firstParamjest to typ obiektu, a secondParamjest to ciąg adresu URL, ale gdy mam, zawsze narzeka, że ​​ten typ jest nieprawidłowy.

Jak mogę zadeklarować wiele eksportów module.w tym przypadku?


2
Najwyraźniej brakuje mi kluczowej części tego paradygmatu, ponieważ wywala mnie to, czego potrzeba, aby to zadziałało.
— Joshua Pinter,

Odpowiedzi:


540

Możesz zrobić coś takiego:

module.exports = {
    method: function() {},
    otherMethod: function() {},
};

Lub tylko:

exports.method = function() {};
exports.otherMethod = function() {};

Następnie w skrypcie wywołującym:

const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');

25
Zawsze używaj module.exports = {}i nie module.method = .... stackoverflow.com/a/26451885/155740
— Scotty

9
module.methodNigdzie tu nie używam ... tylko exports.method, co jest tylko odniesieniemmodule.exports.method , więc zachowuje się tak samo. Jedyną różnicą jest to, że nie zdefiniowaliśmy module.exports, więc domyślnie {}, chyba że się mylę.
— zacier

@mash będzie działać w innym pliku przy użyciu: var otherMethod = require('module.js')(otherMethod); ? Tj. Czy ta linia wymagałaby otherMethodfunkcji tak, jakby była jedyną funkcją na stronie, a eksport był module.exports = secondMethod;:?
— YPCrumble

3
@YPCrumble możesz zrobić var otherMethod = require('module.js').otherMethod .
— zacier

Czy możesz pokazać wymagania dotyczące dopasowania w innym programie, który by do tego pasował?
— NealWalters,

137

Aby wyeksportować wiele funkcji, możesz po prostu wymienić je w następujący sposób:

module.exports = {
   function1,
   function2,
   function3
}

A następnie, aby uzyskać do nich dostęp w innym pliku:

var myFunctions = require("./lib/file.js")

Następnie możesz wywołać każdą funkcję, wywołując:

myFunctions.function1
myFunctions.function2
myFunctions.function3

1
Idealna odpowiedź, ta odpowiedź powinna być oznaczona jako właściwa.
— Wisznu Ranganathan

Jak korzystaliście require("./lib/file.js")? Muszę użyć require("../../lib/file.js"), inaczej to nie zadziała.
— Antonio Ooi,

11
Możesz to zrobić również podczas uzyskiwania do nich dostępu: const { function1, function2, function3 } = require("./lib/file.js")co pozwala na bezpośrednie dzwonienie do nich (np. function1Zamiast myFunctions.function1)
— David Yeiser,

To najczystsze i najprostsze podejście!
— Zeus,

42

oprócz odpowiedzi @mash polecam zawsze wykonać następujące czynności:

const method = () => {
   // your method logic
}

const otherMethod = () => {
   // your method logic 
}

module.exports = {
    method, 
    otherMethod,
    // anotherMethod
};

Uwaga tutaj:

  • Możesz zadzwonić methodzotherMethod i będziesz tego bardzo potrzebować
  • W razie potrzeby możesz szybko ukryć metodę jako prywatną
  • Dla większości IDE jest to łatwiejsze do zrozumienia i autouzupełniania twojego kodu;)
  • Możesz również użyć tej samej techniki do importowania:

    const {otherMethod} = require('./myModule.js');


Zauważ, że używa to skrótu inicjalizatora obiektów es6 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
— chrismarx

1
To jest lepsza odpowiedź imho, ponieważ dotyczy metody dostępu do metody otherMethod. Dzięki za zwrócenie na to uwagi.
— Jeff Beagley,

15

To jest tylko moje odniesienie, ponieważ to, co próbowałem osiągnąć, może zostać osiągnięte przez to.

w module.js

Możemy zrobić coś takiego

    module.exports = function ( firstArg, secondArg ) {

    function firstFunction ( ) { ... }

    function secondFunction ( ) { ... }

    function thirdFunction ( ) { ... }

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

    }

w main.js

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

10

module.js:

const foo = function(<params>) { ... }
const bar = function(<params>) { ... } 

//export modules
module.exports = {
    foo,
    bar 
}

main.js:

// import modules
var { foo, bar } = require('module');

// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);

8

Jeśli pliki są zapisywane przy użyciu eksportu ES6, możesz napisać:

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

8

Jednym ze sposobów na to jest utworzenie nowego obiektu w module zamiast jego zamiany.

na przykład:

var testone = function () {
    console.log('test one');
};
var testTwo = function () {
    console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;

i zadzwonić

var test = require('path_to_file').testOne:
testOne();

Wydało mi się to bardzo prostym podejściem w porównaniu z innymi odpowiedziami! Naprawdę ładne
— HN Singh

6

Możesz napisać funkcję, która ręcznie deleguje między innymi funkcjami:

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

Jest to sposób na osiągnięcie przeciążenia funkcji, ale nie jest bardzo ... elegancki. Myślę, że odpowiedź Masha jest czystsza i lepiej pokazuje zamiary.
— Nepoxx,

5

Użyj tego

(function()
{
  var exports = module.exports = {};
  exports.yourMethod =  function (success)
  {

  }
  exports.yourMethod2 =  function (success)
  {

  }


})();

3

Dwa typy importu i eksportu modułu.

typ 1 (module.js):

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

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

typ 1 (main.js):

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

typ 2 (module.js):

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

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

typ 2 (main.js):

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

Jak korzystać z modułu importu?

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

3

możesz także wyeksportować go w ten sposób

const func1 = function (){some code here}
const func2 = function (){some code here}
exports.func1 = func1;
exports.func2 = func2;

lub dla takich anonimowych funkcji

    const func1 = ()=>{some code here}
    const func2 = ()=>{some code here}
    exports.func1 = func1;
    exports.func2 = func2;

2

moduł1.js:

var myFunctions = { 
    myfunc1:function(){
    },
    myfunc2:function(){
    },
    myfunc3:function(){
    },
}
module.exports=myFunctions;

main.js

var myModule = require('./module1');
myModule.myfunc1(); //calling myfunc1 from module
myModule.myfunc2(); //calling myfunc2 from module
myModule.myfunc3(); //calling myfunc3 from module

2

Można to zrobić na wiele sposobów, jeden ze sposobów wymieniono poniżej. Załóżmy, że masz taki plik .js.

let add = function (a, b) {
   console.log(a + b);
};

let sub = function (a, b) {
   console.log(a - b);
};

Możesz wyeksportować te funkcje za pomocą następującego fragmentu kodu,

 module.exports.add = add;
 module.exports.sub = sub;

Możesz użyć wyeksportowanych funkcji za pomocą tego fragmentu kodu,

var add = require('./counter').add;
var sub = require('./counter').sub;

add(1,2);
sub(1,2);

Wiem, że to późna odpowiedź, ale mam nadzieję, że to pomoże!


0
module.exports = (function () {
    'use strict';

    var foo = function () {
        return {
            public_method: function () {}
        };
    };

    var bar = function () {
        return {
            public_method: function () {}
        };
    };

    return {
        module_a: foo,
        module_b: bar
    };
}());

0

Jeśli zadeklarujesz klasę w pliku modułu zamiast prostego obiektu

Plik: UserModule.js

//User Module    
class User {
  constructor(){
    //enter code here
  }
  create(params){
    //enter code here
  }
}
class UserInfo {
  constructor(){
    //enter code here
  }
  getUser(userId){
    //enter code here
    return user;
  }
}

// export multi
module.exports = [User, UserInfo];

Główny plik: index.js

// import module like
const { User, UserInfo } = require("./path/to/UserModule");
User.create(params);
UserInfo.getUser(userId);

0

Możesz także użyć tego podejścia

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

lub

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

0

Dodanie tutaj, aby ktoś mógł pomóc:

ten blok kodu pomoże dodać wiele wtyczek do cypress index.js Wtyczki -> cypress-ntlm-auth i wybór pliku env cypress

const ntlmAuth = require('cypress-ntlm-auth/dist/plugin');
const fs = require('fs-extra');
const path = require('path');

const getConfigurationByFile = async (config) => {
  const file = config.env.configFile || 'dev';
  const pathToConfigFile = path.resolve(
    '../Cypress/cypress/',
    'config',
    `${file}.json`
  );
  console.log('pathToConfigFile' + pathToConfigFile);
  return fs.readJson(pathToConfigFile);
};

module.exports = async (on, config) => {
  config = await getConfigurationByFile(config);
  await ntlmAuth.initNtlmAuth(config);
  return config;
};
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.