๐ŸŸจ JavaScript

[JavaScript] ํŒŒ์ผ ๋ชจ๋“ˆํ™”(module)

10000COW 2022. 12. 24. 10:47
728x90

ํŒŒ์ผ ๋ชจ๋“ˆํ™”

๋ชจ๋“ˆ(module)์„ ์‚ฌ์šฉํ•˜๋ฉด JavaScript ํŒŒ์ผ๋ณ„๋กœ ๊ฐ๊ฐ ์บก์Šํ™”๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.


๋‘ ๊ฐœ์˜ JavaScript ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์„œ ๋ชจ๋“ˆํ™”๋ฅผ ํ•ด๋ณด์ž.

์šฐ์„ , ์•„๋ž˜์™€ ๊ฐ™์ด HTML ํŒŒ์ผ์— counter.js ํŒŒ์ผ๊ณผ main.js ํŒŒ์ผ์„ <script> ํƒœ๊ทธ๋กœ ์—ฐ๊ฒฐํ•ด๋ณด์ž.

 

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="module" src="counter.js"></script>
    <script type="module" src="main.js"></script>
  </head>
  <body></body>
</html>

counter.js ํŒŒ์ผ์—๋Š” ๋ณ€์ˆ˜ count๊ฐ€ ์žˆ๊ณ , ํ•จ์ˆ˜ increase์™€ getCount๊ฐ€ ์žˆ๋‹ค.

๋ณ€์ˆ˜ count๋Š” ๋‹ค๋ฅธ ํŒŒ์ผ์—์„œ ์ ‘๊ทผํ•˜์ง€ ๋ชปํ•˜๊ฒŒ ํ•˜๊ณ , increase์™€ getCount๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒํ•˜๋ ค๋ฉด

export๋ฅผ ์•ž์— ๋ถ™์—ฌ์ฃผ๋ฉด ๋‹ค๋ฅธ ํŒŒ์ผ์—์„œ import๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

(export default๋Š” ๋ชจ๋“ˆ์—์„œ ๋”ฑ ํ•˜๋‚˜๋งŒ exportํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.)

counter.js

let count = 0;
export function increase() {
  count++;
  console.log(count);
}
export function getCount() {
  return count;
}

main.js๋Š” import๋ฅผ ํ™œ์šฉํ•ด counter.js๋กœ ๋ถ€ํ„ฐ increase ํ•จ์ˆ˜์™€ getCount ํ•จ์ˆ˜๋ฅผ ๋ฐ›์•„์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

(count๋Š” export๋˜์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ ๋ถˆ๊ฐ€)

 

import * ์„ ์‚ฌ์šฉํ•˜๋ฉด counter.js ํŒŒ์ผ์ด exportํ•˜๋Š” ๋ชจ๋“  ๊ฒƒ์„ ๋ฐ›์•„์˜ค๊ณ ,

์ด๋Ÿฐ ์‹์œผ๋กœ ์›ํ•˜๋Š” ๊ฒƒ๋งŒ ๋ฐ›์•„์˜ฌ ์ˆ˜๋„ ์žˆ๋‹ค.

import { increase} from './counter.js'; 

import { increase, getCount } from './counter.js'

 

main.js

import * as counter from './counter.js';

counter.increase();
counter.increase();
counter.increase();
console.log(counter.getCount());

 

728x90