> For the complete documentation index, see [llms.txt](https://docs.sysout.co.kr/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sysout.co.kr/web/develop-page/js/syntax/module.md).

# module

## module

**module**은 프로그램을 단위 별로 개발하여 필요한 내용들을 불러와 사용할 수 있도록 고안된 시스템이다. **export**와 **import**를 통하여 내보내기 및 불러오기를 처리할 수 있다.

{% embed url="<https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Modules>" %}

## module의 장점

module의 장점은 다음과 같다.

* export를 통해 원하는 항목만 외부에서 이용하도록 처리할 수 있다.
* import를 통해 대상에서 원하는 항목만 호출하여 사용할 수 있다.
* cdn처럼 선언 순서가 중요하지 않다.

## module 사용을 위한 script 구성

**module**을 사용하기 위해서는 다음과 같은 <mark style="color:green;">`<script>`</mark>구성이 필요하다.

```markup
<script type="module">

</script>
```

## named export

이름을 기반으로 하여 export와 import를 할 수 있다. 프로젝트를 다음과 같이 구성하여 module을 사용해본다.

```
project
+-- test01.html
+-- test01.js
```

{% code title="test01.js" %}

```javascript
export const a = 10;
export const b = 20;
```

{% endcode %}

`test01.html`에서는 script 부분 외는 기본 템플릿을 사용한다.

{% code title="test01.html" %}

```markup
<script type="module">
import {a, b} from './test01.js';
console.log(a, b);
</script>
```

{% endcode %}

실행하면 정상적으로 값이 로드되어 출력까지 잘 되는 것을 확인할 수 있다.

<div align="left"><figure><img src="/files/hFNRRnKU5uNaNxLL16l8" alt=""><figcaption></figcaption></figure></div>

## CDN 방식과의 비교

cdn 방식이라면 위의 예제는 다음과 같이 구현되었을 것이다.

{% code title="test01.js" %}

```javascript
const a = 10;
const b = 20;
```

{% endcode %}

{% code title="test01.html" %}

```markup
<script src="./test01.js"></script>
<script>
console.log(a, b);
</script>
```

{% endcode %}

**import** 대신 <mark style="color:green;">**`<script>`**</mark> 태그를 사용하여 js 파일을 불러와 해당 파일의 내용을 사용한다. 이 경우 발생하는 문제점은 여러 가지가 있다.

1. js에 작성된 내용의 이름을 바꿀 수 없다.
2. js에 작성된 내용을 반드시 모두 가져와야 한다.
3. 불러오는 <mark style="color:green;">**`<script>`**</mark>를 반드시 위에 따로 작성해야 한다.

<div align="left"><figure><img src="/files/WrRPlMZ3ngNNKX5ko6D2" alt=""><figcaption></figcaption></figure></div>

## export default

default를 사용하여 이름을 생략하고 export와 import를 할 수 있다. 프로젝트를 다음과 같이 구성한다.

```
project
+-- test02.html
+-- test02.js
```

js와 html에 각각 코드를 작성한다.

{% code title="test02.js" %}

```javascript
export default function hello() {
    console.log("Hello world!");
}
```

{% endcode %}

{% code title="test02.html (script 부분만)" %}

```html
<script type="module">
import hello from './test02.js';
hello();
</script>
```

{% endcode %}

아래의 그림처럼 불러오며, [#named-export](#named-export "mention")와 차이점은 import 시 **`{ }`**&#xB97C; 사용하지 않는다는 것이다.

<div align="left"><figure><img src="/files/TQ84ft7mLqJo6vFzJNmc" alt=""><figcaption></figcaption></figure></div>

{% hint style="info" %}
다음 두 코드는 같은 코드이다.

```javascript
import hello from './test02.js';
```

```javascript
import {default as hello} from './test02.js';
```

참고 링크<https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Modules#default_exports_versus_named_exports>
{% endhint %}

## rename import

**import** 할 때 충돌을 방지하기 위해서 이름을 변경할 수 있다. 프로젝트를 다음과 같이 구성한다.

```
project
+-- test03.html
+-- test03.js
```

{% code title="test03.js" %}

```javascript
const n = 10;
const str = "hello";
function alert() {
    console.log("module test");
}

export {n, str, alert};
```

{% endcode %}

{% code title="test03.html (이름 변경 전)" %}

```markup
<script type="module">
import {n, str, alert} from './test03.js';

console.log(n);
console.log(str);
alert();
</script>
```

{% endcode %}

실행하면 정상적으로 나오지만 `alert`과 같은 경우 `window.alert` 함수와 충돌이 발생한다. 따라서 이름을 바꿔서 불러올 수 있다. 이름을 바꾼 코드는 다음과 같다.

{% code title="test03.html (이름 변경 후)" %}

```markup
<script type="module">
import {n as a, str as b, alert as c} from './test03.js';

console.log(a);
console.log(b);
c();
</script>
```

{% endcode %}

## default rename import

export default에 대한 rename은 다음과 같이 할 수 있다.

```
project
+-- test04.html
+-- test04.js
```

{% code title="test04.js" %}

```javascript
export default function hello(){
    console.log("Hello!");
}
```

{% endcode %}

{% code title="test04.html (script 부분만)" %}

```markup
<script type="module">
import goodbye from './test04.js';
goodbye();
</script>
```

{% endcode %}
