Node.js'de birden fazla module.exports bildirin


243

Ne elde etmeye çalışıyorum içinde birden çok işlev içeren bir modül oluşturmaktır.

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

Ben sorun firstParambir nesne türü ve secondParambir URL dize olmasıdır, ama ben her zaman tür yanlış olduğunu şikayet ediyor.

Bu durumda birden fazla module.exports'u nasıl bildirebilirim?


2
Bu paradigmanın bazı önemli kısımlarını açıkça özlüyorum çünkü bunun işe yaraması için beni uçuruyor.
— Joshua Pinter

Yanıtlar:


540

Gibi bir şey yapabilirsiniz:

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

Ya da sadece:

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

Sonra çağıran komut dosyasında:

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

25
Her zaman kullanın module.exports = {}ve kullanmayın module.method = .... stackoverflow.com/a/26451885/155740
— Scotty

9
module.methodBurada hiçbir yerde kullanmıyorum ... sadece exports.method, bu sadece bir referans module.exports.method, bu yüzden aynı şekilde davranıyor. Tek fark, tanımlamadığımızdır module.exports, bu yüzden {}yanılmıyorsam varsayılan olarak.
— püre

: @mash kullanarak başka dosyada bu işi olur var otherMethod = require('module.js')(otherMethod);? Yani, bu satır otherMethod, sayfadaki tek işlevmiş gibi dışa aktarma işlevi gerektiriyor module.exports = secondMethod;mu ve dışa aktarma:?
— YPCrumble

3
@YPC yapabilirsin var otherMethod = require('module.js').otherMethod.
— mash

Bununla ilgili diğer programda eşleştirme gereksinimlerini gösterebilir misiniz?
— NealWalters

137

Birden fazla işlevi dışa aktarmak için bunları şu şekilde listeleyebilirsiniz:

module.exports = {
   function1,
   function2,
   function3
}

Ve sonra başka bir dosyada onlara erişmek için:

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

Ve sonra her bir işlevi çağırarak arayabilirsiniz:

myFunctions.function1
myFunctions.function2
myFunctions.function3

1
Mükemmel cevap, bu cevap doğru cevap olarak işaretlemem gerekir.
— Vishnu Ranganathan

Siz nasıl kullandınız require("./lib/file.js")? Kullanmam gerek require("../../lib/file.js"), aksi takdirde işe yaramaz.
— Antonio Ooi

11
Bunlara erişirken de yapabilirsiniz: bu da const { function1, function2, function3 } = require("./lib/file.js")onları doğrudan aramanızı sağlar (örneğin function1yerine myFunctions.function1)
— David Yeiser

Bu en temiz ve en basit yaklaşım!
— Zeus

42

@mash yanıtına ek olarak her zaman aşağıdakileri yapmanızı öneririm:

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

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

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

Buraya dikkat edin:

  • Sen diyebilirsin methodgelen otherMethodve bu çok ihtiyacınız olacak
  • İhtiyacınız olduğunda bir yöntemi hızlı bir şekilde gizli olarak gizleyebilirsiniz
  • Bu, çoğu IDE'nin kodunuzu anlaması ve otomatik tamamlaması için daha kolaydır;)
  • Aynı tekniği içe aktarma için de kullanabilirsiniz:

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


Bunun es6 nesne başlatıcı kısayolunu kullandığını unutmayın - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
— chrismarx

1
Bu, otherMethod'a erişme yöntemine yönelik olduğu için daha iyi yanıt imho'dur. Bunu işaret ettiğiniz için teşekkürler.
— Jeff Beagley

15

Bu sadece benim referansımdır çünkü elde etmeye çalıştığım şey bununla başarılabilir.

İçinde module.js

Böyle bir şey yapabiliriz

    module.exports = function ( firstArg, secondArg ) {

    function firstFunction ( ) { ... }

    function secondFunction ( ) { ... }

    function thirdFunction ( ) { ... }

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

    }

İçinde 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

Dosyalar ES6 dışa aktarma kullanılarak yazıldıysa, şunları yazabilirsiniz:

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

8

Bunu yapmanın bir yolu, modülde değiştirmek yerine yeni bir nesne oluşturmaktır.

Örneğin:

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

ve aramak

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

Bu bana diğer cevaplara kıyasla çok basit bir yaklaşım gibi geldi! Gerçekten güzel
— HN Singh

6

Diğer işlevler arasında el ile temsilci atanan bir işlev yazabilirsiniz:

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

Bu, işlev aşırı yüklemesi elde etmenin bir yoludur, ancak çok ... zarif değildir. Bence Mash'in cevabı daha temiz ve daha iyi niyet gösteriyor.
— Nepoxx

5

bunu kullan

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

  }
  exports.yourMethod2 =  function (success)
  {

  }


})();

3

İki tip modül alma ve verme.

tip 1 (module.js):

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

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

tip 1 (main.js):

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

tip 2 (module.js):

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

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

tip 2 (main.js):

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

Alma modülü nasıl kullanılır?

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

3

ayrıca bu şekilde dışa aktarabilirsiniz

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

veya bunun gibi anonim işlevler için

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

2

module1.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

Bunu yapmanın birden fazla yolu vardır, bir yol aşağıda belirtilmiştir. Bunun gibi .js dosyanız olduğunu varsayalım.

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

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

Aşağıdaki kod snippet'ini kullanarak bu işlevleri dışa aktarabilirsiniz,

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

Dışa aktarılan işlevleri bu kod snippet'ini kullanarak kullanabilirsiniz,

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

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

Bunun geç bir cevap olduğunu biliyorum, ama umarım bu yardımcı olur!


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

Basit nesne yerine modül dosyasında bir sınıf bildirirseniz

Dosya: 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];

Ana Dosya: index.js

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

0

Bu yaklaşımı da kullanabilirsiniz

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

veya

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

0

Birinin yardım etmesi için buraya ekleme:

Bu kod bloğu, selvi index.js'ye birden fazla eklenti eklenmesine yardımcı olacaktır. Eklentiler -> cypress-ntlm-auth ve selvi env dosyası seçimi

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;
};
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.