JS 모듈

gang_shik·2025년 3월 19일
0

JavaScript

목록 보기
22/23

모듈이란?

  • 모듈은 독립적인 특성을 가진 기능 단위의 부품
  • 프로그램의 기능을 독립적인 부품으로 분리한 것, 동시에 여러 다른 모듈과 함께 조합하여 재사용될 수 있음
  • 여기서 중요한 것은 내가 만든 코드가 어떻게 재활용 할 수 있는가도 중요함
  • 예전에는 즉시 실행함수, 클로저등으로 모듈로 응용해서 썼지만, 요즘에는 이러한 모듈을 지원을 해 줌

CommonJS

  • JS 커뮤니티에서 만든 모듈 시스템임, NodeJS 모듈도 CommonJS로 이루어져있음(모듈 사용이 용이함)
  • 아래와 같이 별도의 파일로 저장된 것에 대해서 모듈을 써서 할 수 있음
// CommonJS (Export)
function Person(name, age, location) {
  this.name = name;
  this.age = age;
  this.location = location;

  this.getName = function () {
    return this.name + '입니다';
  };
}

module.exports = Person;
// CommonJS (Import)
// require를 통해서 모듈을 불러와서 사용함
const Person = require('./02-CommonJS-person');

const me = new Person('kevin', 10, 'Korea');
const you = new Person('hart', 20, 'USA');

console.log(me.getName());
console.log(you.getName());
  • 다양한 파일을 가져오고 다양한 함수, 객체등을 불러와서 처리할 수 있음, 이를 통해서 굳이 복잡하게 파일을 구성하지 않고 파일을 여러개 나누고 분리해서 재활용을 할 수 있음
  • 파일 단위로 나눠서 편하게 할 수 있음

amd

  • Asynchronous Module Definition의 약자, 모듈을 선언하면서 의존하고 있는 모듈을 함께 명시, 비동기적으로 의존 모듈을 불러옴
  • 왜냐하면 CommonJS는 동기적으로 쓰기 때문임
  • 아래와 같이 별도의 정의 문법을 바탕으로 사용할 수 있음
define(['module'], function(module) {
  return function() {

  }
})
  • CommonJS는 서버에서 쓰면서 동기적으로 동작하고 amd의 경우 브라우저에서도 동작할 수 있고 비동기적인 특성을 가짐
  • amd를 주로 쓰지 않지만 특성을 알아두면 좋음

umd

  • Universal Module Definition으로 AMD와 CommonJS 두 방식 모두 지원하고 클라이언트, 서버 어디에서나 작동함
  • 아래와 같이 적용되서 쓸 수 있음
(function (root, factory) {
  if (typeof exports === 'object' && module.exports) {
    // CommonJS
    module.exports = factory(require('module'))
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(['module'], function (module) { })
  } else {
    // 전역 공간
    root.global = factory(root.module)
  }
}(this, function (module) {
  // 실제 모듈
}))

es-module

  • es-module은 최신 브라우저에서만 동작함, 아래와 같이 간단하게 키워드만을 통해서 쓸 수 있음
export const a = 'a';

export function hello() {
  return 'hello';
}

export { a, hello };
import { a, hello } from './05-es-module-export.js';
// as 키워드로 이름을 바꿀 수도 있음
// import * as i from './05-es-module-export.js';

console.log(a);
console.log(hello());
  • 기본 내보내기와 기본 가져오기는 아래와 같이 할 수 있음, 해당 파일에서 내보내는 것이 기본이라 중괄호 없이 쓴 것
function hello() {
  return 'hello';
}

export default hello;
import h from './05-es-module-default-export';

console.log(h());
  • 브라우저에서도 아래와 같이 script 타입을 모듈로 지정해서 쓸 수 있음
<!DOCTYPE html>
<html lang="ko">
  <head>
    <title>Zero base</title>
    <meta charset="utf-8" />
    <script type="module" src="./05-es-module-export.js"></script>
    <script type="module" src="./05-es-module-default-export.js"></script>
  </head>

  <body></body>
</html>
const a = 'a';

function hello() {
  return 'hello';
}

export { a, hello };
  • 이 때 위의 경우 모듈을 순서대로 가져오는데 async 키워드를 붙이면 예측할 수 없음(비동기로 불러오니까)
    <script async type="module" src="./05-es-module-export.js"></script>
    <script async type="module" src="./05-es-module-default-export.js"></script>
  • 아래와 같이 되는 것을 확인가능함
<!DOCTYPE html>
<html lang="ko">
  <head>
    <title>Zero base</title>
    <meta charset="utf-8" />
    <script type="module" src="./05-es-module-export.js"></script>
    <script type="module">
      import { a, hello } from './05-es-module-export.js';
      
      console.log(a);
      console.log(hello());
    </script>
  </head>

  <body></body>
</html>
profile
측정할 수 없으면 관리할 수 없고, 관리할 수 없으면 개선시킬 수도 없다

0개의 댓글