Node.js

nodejs 외부 js파일(모듈) 함수 호출하기

blackbearwow 2022. 7. 20. 14:17

CommonJS방식

1. module.exports = {} 안에 함수들을 선언하면 된다. 그러면 외부 js파일에서도 변수를 선언해 함수를 호출할 수 있다.

// tools1.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

let zemba = function () {
}

2. 또는 함수를 선언 후 module.exports{}를 해줘도 된다.

// tools2.js
// ========
function foo() {
	// whatever
}
function bar() {
	// whatever
}
let zemba = function () {
}

module.exports = {foo, bar};

결과

// app.js
// ======
let tools = require('./tools1'); //또는 require('./tools2');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined

 

ES6방식

1. export {} 안에 함수들을 선언하면 된다.

function foo() {
	// whatever
}
function bar() {
	// whatever
}
let zemba = function () {
}
export {foo, bar, zemba};

2. 또는 각 함수마다 export를 앞에 붙인다.

export function foo() {
	// whatever
}
export function bar() {
	// whatever
}
export let zemba = function () {
}

결과

import {foo, bar, zemba} from './tools1.mjs';
console.log(typeof foo); // => 'function'
console.log(typeof bar); // => 'function'
console.log(typeof zemba); // => 'function'

es6방식을 사용하려면, 파일 확장자를 .mjs로 해주어야 한다.

또는 package.json에서 "type":"module"을 지정해주면 .js도 가능하다.


참고: https://stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files

https://jamesmccaffrey.wordpress.com/2019/01/31/calling-functions-from-another-file-in-node-js/