study/Node.js & NestJS

import vs require

836586697769 2024. 5. 30. 20:07
💡 JavaScript에서 외부 모듈을 가져오는 데 사용하는 키워드

 

require / exports

  • Node.js에서 사용되고 있는 CommonJS 모듈 시스템에서 사용됨
  • 모듈을 동기적으로 가져옴
  • CommonJS에서는 동적 모듈 로딩에 더 적합함
    • CommonJS에서는 모듈을 파일 단위로 정의하고 각 파일은 독립적인 모듈로 간주됨
    • CommonJS 모듈은 동기적으로 로드되므로 모듈을 처음 로드할 때 모듈의 코드를 실행하고 module.exports된 객체를 반환함
(1)
// 모듈 정의 (module.js)
const name = '이름';
module.exports = name;

//모듈 로드
const name = require('./module');

(2)
// 모듈 정의
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = { add, subtract };

// 모듈 로드
const module = require('./module');
const result = module.add(5, 3);

(3)
// 모듈 정의
exports.name = '이름';
exports.add = (a, b) => a + b;
exports.Person = class Person { constructor(name){ this.name = name; }}

// 모듈 로드
const { name, add, Person } = require('./module');
console.log(add(5, 3)); // 8
const person = new Person(name);
console.log(person); // Person { name: '이름' }

 

import / export

  • ES6 모듈 시스템에서 사용됨
  • 모듈을 비동기적으로 가져옴
  • ES 모듈 시스템은 정적 모듈 로딩에 더 적합함
    • ES 모듈은 비동기적으로 로드되어 클라이언트 사이드 애플리케이션에 더 적합함
  • 사용자가 필요한 부분 만 선택하고 로드 가능
  • require보다 성능이 우수함
(1)
// 모듈 정의
const name = '이름';
export default name;

//모듈 로드
import name from './module'

(2)
// 모듈 정의
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// 모듈 로드
import { add, subtract } from './module';
const result = add(5, 3);

(3)
// 모듈 정의
export const name = '이름';
export function add(a, b) { return a + b; }
export class Person { constructor(name){ this.name = name; }}

// 모듈 정의 2
const name = '이름';
function add() { return a + b; }
class Person { constructor(name){ this.name = name; }}
export { name, add, Person };

// 모듈 로드 1
import { name, add, Person } from './module';
console.log(add(5, 3)); // 8
const person = new Person(name);
console.log(person); // Person { name: '이름' }

// 모듈 로드 2
import * as obj from './module'; 
console.log(obj.add(5, 3)); // 8
const person = new obj.Person(name);
console.log(person); // Person { name: '이름' }