ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

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
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
ยซ   2025/01   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ
250x250