Node.js에서 module.exports를 여러 개 선언합니다.
제가 달성하고자 하는 것은 여러 기능을 포함하는 하나의 모듈을 만드는 것입니다.
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 문자열이지만, 해당 문자열이 있을 때는 항상 유형이 잘못되었다고 불평합니다.
이 경우 module.exports를 여러 개 선언하려면 어떻게 해야 합니까?
다음과 같은 작업을 수행할 수 있습니다.
module.exports = {
method: function() {},
otherMethod: function() {},
};
아니면 그냥:
exports.method = function() {};
exports.otherMethod = function() {};
그런 다음 호출 스크립트에서:
const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');
여러 기능을 내보내려면 다음과 같이 나열하면 됩니다.
module.exports = {
function1,
function2,
function3
}
그런 다음 다른 파일로 액세스합니다.
var myFunctions = require("./lib/file.js")
그런 다음 다음 다음을 호출하여 각 함수를 호출할 수 있습니다.
myFunctions.function1
myFunctions.function2
myFunctions.function3
@mash 답변 외에도 항상 다음을 수행할 것을 권장합니다.
const method = () => {
// your method logic
}
const otherMethod = () => {
// your method logic
}
module.exports = {
method,
otherMethod,
// anotherMethod
};
참고:
- 전화할 수 있습니다.
methodotherMethod그리고 당신은 이것이 많이 필요할 것입니다. - 필요할 때 메소드를 개인적인 것으로 빠르게 숨길 수 있습니다.
- 대부분의 IDE가 코드를 이해하고 자동 완성하는 것이 더 쉽습니다 ;)
가져오기에도 동일한 방법을 사용할 수 있습니다.
const {otherMethod} = require('./myModule.js');
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>);
이것은 제가 성취하고자 했던 것이 이것으로 성취될 수 있기 때문에 참고하기 위한 것입니다.
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);
ES6 내보내기를 사용하여 파일을 작성한 경우 다음을 작성할 수 있습니다.
module.exports = {
...require('./foo'),
...require('./bar'),
};
한 가지 방법은 새 개체를 교체하는 대신 모듈에 새 개체를 생성하는 것입니다.
예:
var testone = function () {
console.log('test one');
};
var testTwo = function () {
console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;
그리고 전화하기
var test = require('path_to_file').testOne:
testOne();
다른 기능 간에 수동으로 위임하는 기능을 작성할 수 있습니다.
module.exports = function(arg) {
if(arg instanceof String) {
return doStringThing.apply(this, arguments);
}else{
return doObjectThing.apply(this, arguments);
}
};
이를 수행하는 방법은 여러 가지가 있으며, 한 가지 방법이 아래에 설명되어 있습니다.이런 .js 파일이 있다고 가정해 보세요.
let add = function (a, b) {
console.log(a + b);
};
let sub = function (a, b) {
console.log(a - b);
};
다음 코드 스니펫을 사용하여 이러한 함수를 내보낼 수 있습니다.
module.exports.add = add;
module.exports.sub = sub;
내보낸 함수는 이 코드 조각을 사용하여 사용할 수 있습니다.
var add = require('./counter').add;
var sub = require('./counter').sub;
add(1,2);
sub(1,2);
답장이 늦은 건 알지만 도움이 되길 바랍니다!
이것을 사용합니다.
(function()
{
var exports = module.exports = {};
exports.yourMethod = function (success)
{
}
exports.yourMethod2 = function (success)
{
}
})();
또한 당신은 이렇게 그것을 수출할 수 있습니다.
const func1 = function (){some code here}
const func2 = function (){some code here}
exports.func1 = func1;
exports.func2 = func2;
또는 이와 같은 익명의 기능을 위해.
const func1 = ()=>{some code here}
const func2 = ()=>{some code here}
exports.func1 = func1;
exports.func2 = func2;
제가 아래에 했던 것처럼 사용할 수 있습니다.기능 및 화살표 기능 모두에 대해:
greet.js :
function greetFromGreet() {
console.log("hello from greet module...");
}
const greetVar = () => {
console.log("greet var as a arrow fn/...");
};
module.exports = { greetVar, greetFromGreet }; // ---- multiple module export...
// -----------------------------------------------
app.js :
const greetFromGreets = require("./greet");
greetFromGreets.greetFromGreet();
greetFromGreets.greetVar();
// -----------------------------------------------
노드 모듈 내에서 다음과 같은 다양한 기능을 내보낼 수 있습니다.
module.exports.eat = eat;
function eat() {
.......
return *something*;
};
module.exports.sleep = sleep;
function sleep() {
.......
return *something*;
};
내보내기 중에는 함수를 호출하지 않습니다.그런 다음 모듈이 필요할 때 다음과 같이 요구할 수 있습니다.
const task = require(__dirname + "/task.js");
//task is the name of the file
let eat = task.eat();
let sleep = task.sleep();
두 가지 유형의 모듈 가져오기 및 내보내기.
유형 1(802.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(802.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"),
};
모듈 1.js:
var myFunctions = {
myfunc1:function(){
},
myfunc2:function(){
},
myfunc3:function(){
},
}
module.exports=myFunctions;
메인.js
var myModule = require('./module1');
myModule.myfunc1(); //calling myfunc1 from module
myModule.myfunc2(); //calling myfunc2 from module
myModule.myfunc3(); //calling myfunc3 from module
내보내기 키워드 사용
module.js
export {method1, method2}
다음으로 가져오기main.js
import {method1, method2) from "./module"
단순 개체 대신 모듈 파일에서 클래스를 선언하는 경우
파일: 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];
주 파일: index.js
// import module like
const { User, UserInfo } = require("./path/to/UserModule");
User.create(params);
UserInfo.getUser(userId);
이 접근 방식도 사용할 수 있습니다.
module.exports.func1 = ...
module.exports.func2 = ...
또는
exports.func1 = ...
exports.func2 = ...
도움이 필요한 사용자를 위해 여기에 추가:
이 코드 블록은 사이프러스 인덱스.js 플러그인 -> 사이프러스-ntlm-auth 및 사이프러스 env 파일 선택에 여러 플러그인을 추가하는 데 도움이 됩니다.
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;
};
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
};
}());
언급URL : https://stackoverflow.com/questions/16631064/declare-multiple-module-exports-in-node-js
'programing' 카테고리의 다른 글
| 기록이 있는 SVN 저장소를 새 Git 저장소로 마이그레이션하려면 어떻게 해야 합니까? (0) | 2023.05.29 |
|---|---|
| 원에 불과한 사용자 정의 UI뷰 그리는 방법 - 아이폰 앱 (0) | 2023.05.29 |
| 양식 제출 후 재쿼리 콜백을 수행하는 방법은 무엇입니까? (0) | 2023.05.29 |
| iTunes Connect의 "버전 번호", Xcode의 "번들 버전", "번들 버전 문자열"의 차이점은 무엇입니까? (0) | 2023.05.29 |
| 이클립스 내에서 CSS 사전 처리를 통합하는 방법은 무엇입니까? (0) | 2023.05.29 |