[JavaScript] ํ์ผ ๋ชจ๋ํ(module)
ํ์ผ ๋ชจ๋ํ
๋ชจ๋(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());