module exports / require()
모듈로 다른 파일에서 위해서는 module의 exports속성을 활용하여 내보내고, exports 된 모듈을 이용하기 위해서는 require()로 모듈을 가져온다.
require('파일경로')
// Importing a local module with a path relative to the `__dirname` or current
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
const myLocalModule = require('./path/myLocalModule');
// Importing a JSON file:
const jsonData = require('./path/filename.json');
// Importing a module from node_modules or Node.js built-in module:
const crypto = require('node:crypto');
예시1)
예시2)
>> ES6에서 require대체할 import가 생겼는데, 이 부분은 후에 작성할 예정이다.
module.exports vs exports
var module = { exports: {} };
var exports = module.exports;
// your code
return module.exports;
exports = {} //객체 할당 X
module.exports = {} //객체 할당 O
exports.kwak = 5; //속성 할당 O
module.exports.kwak = 5 //속성 할당 O
module.exports는 빈 오브젝트로 초기화되어 있으므로 exports 변수를 통해 프로퍼티를 추가할 수 있지만, exports에 새로운 객체를 할당하면 module.exports와는 상관 없는 변수가 되어버리므로 모듈이 동작하지 않는다.
1) exports
// square.js
exports.area = (width) => width * width;
exports.perimeter = (width) => 4 * width;
// app.js
const square = require('./square');
console.log(square.area(3));
console.log(square.perimeter(3));
2) module.exports
module.exports 변수에 아예 새로운 객체를 할당 or 프로퍼티 할당도 가능
// square.js
module.exports = {
area: (width) => width * width,
perimeter: (width) => 4 * width
}