CommonJS방식

1. 전체 모듈로써 내보내고 전체를 하나의 Obj로 받아서 사용하는 방법(가장 추천하는 방식)

const animals = ["dog", "cat"];

function showAnimals() {
  animals.map((el) => console.log(el));
} // animals배열의 각 요소를 출력 

module.exports = {
  animals,
  showAnimals,
};
const animals = require("./animal");

console.log(animals);
animals.showAnimals;

module.js 실행 결과

module.js 실행 결과

2. 내보내고 싶은 것(변수, 함수, 클래스 등등)에 exports를 붙여서 내보내고,각각을 따로 선언해서 가져 오는 방식

const animals = ["dog", "cat"];

exports.animals = animals;

exports.showAnimals = function showAnimals() {
  animals.map((el) => console.log(el));
};
const { animals, showAnimals } = require("./animal");

console.log(animals);
showAnimals();
const animalModule = require("./animal");

console.log(animalModule.animals); // ["dog", "cat"]
animalModule.showAnimals(); // "dog", "cat" 출력

module 실행 결과

module 실행 결과

3. 하나의 객체(or 클래스)에 전부를 넣어놓고 그 객체 자체를 내보내는 방식