IdoCleanCode
article thumbnail
Published 2024. 10. 6. 14:47
[Node.js] ESM Tutorials/Node
반응형

ESM(ECMscript Modulse)은 자바스크립트의 표준화 모듈 시스템입니다. 파일간의 변수, 함수, 객체등을 공유 하기위해 가져오기 내보내기 문을 사용합니다

 

1. 정의

ESM은 ES6(ES2015)에서 도입된 모듈  시스템으로. 자바스크립트 파일을 모듈로 관리하여 각 파일이 독립적인 스코프를 가집니다.

 

2. 사용법

모듈 내보내기: export 키워드를 사용합니다.

// myModule.mjs
export const myVariable = 42;
export function myFunction() {
    console.log("Hello from myFunction!");
}

 

모듈 가져오기: import 키워드를 사용합니다.

// main.mjs
import { myVariable, myFunction } from './myModule.js';
console.log(myVariable); // 42
myFunction(); // "Hello from myFunction!"

 

3.파일 확장자

ESM 모듈은 .js 파일 확장자를 사용하지만, Node.js에서는.mjs 확장자를 사용합니다. package.json 파일에 "type: "module""을추가하면 .js 확장자를 ESM으로 인식합니다.

 

package.json  설정

{
  "name": "my-esm-project",
  "version": "1.0.0",
  "type": "module", // 모듈설정
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC"
}

 

4.비동기 로딩

ESM은 비동기적으로 모듈을 로드 하며 import() 함수를 사용하여 동적으로 모듈을 가져올 수 있습니다.

import('./myModule.js').then(module => {
    module.greet();
});

 

5. 전역 스코프와 Strict Mode

ESM은 전역스코프를 공유하지 않으며, 모든 모듈은 자동으로 strict mode로 실행합니다.

 

 

관련자료

 

https://idocleancode.tistory.com/436

 

[Node.js] 학습 로드맵

Node.js 소개Node.js 이란?    참고자료https://roadmap.sh/nodejs Node.js Developer Roadmap: Learn to become a modern node.js developerLearn to become a modern node.js developer using this roadmap. Community driven, articles, resources, guides, i

idocleancode.tistory.com

 

반응형

'Tutorials > Node' 카테고리의 다른 글

[Node.js] 간단한 입출력 콘솔 프로그램  (0) 2024.10.12
[Node.js] CommonJS  (1) 2024.10.06
[Node.js] Node.js 실행  (0) 2024.10.06
[Node.js] Node.js vs Browser  (0) 2024.10.06
[Node.js] Node.js 이란?  (3) 2024.10.06
profile

IdoCleanCode

@IdoCleanCode

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!