CommonJS 모듈
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 9번째.
npm 패키지와 오래된 튜토리얼에서 읽게 될 Node 코드의 상당수는 다른 모듈 시스템을 사용합니다.
CommonJS는 module.exports로 내보내고 require로 가져옵니다. Node는 여전히 .cjs로 끝나는 파일에서 이 코드를 실행하며, 이러한 파일을 import하면 기본값으로 해당 파일의 module.exports 객체를 가져옵니다.
// greet.cjs
function hello(name) {
return 'Hello, ' + name;
}
module.exports = { hello };
// app.js
import greet from './greet.cjs';
console.log(greet.hello('Ada'));exports는 처음에 module.exports와 같은 객체를 가리킵니다. exports.hello = hello는 여기에 항목을 추가하지만, exports = { hello }는 변수를 다른 객체로 바꾸므로 가져오는 쪽에는 빈 객체가 전달됩니다.
챌린지
쉬움legacy/stats.cjs에서countWords(notes)를 완성하세요. 메모에 모두 몇 개의 단어가 있는지 세면 됩니다.import stats from './legacy/stats.cjs'를 사용해notes.js로 가져오세요.stats명령은3 notes, 7 words를 출력합니다.
node notes.js stats를 실행하세요. 그런 다음 메모를 add하고 stats를 다시 실행하세요. 아직 저장되지 않으므로 여전히 3입니다.
직접 해보기
// CommonJS 방식으로 작성된 오래된 모듈입니다.
function countWords(notes) {
// 모든 notes에 들어 있는 단어의 총개수를 반환합니다.
return 0;
}
module.exports = { countWords };