๐๋ชจ๋ํ์ต
๐MDN๋ชจ๋๋ฌธ์
Info: ๐ข ํ๋ก๊ทธ๋๋ฐ์์ย
๋ชจ๋์ด๋ย ํ๋ก๊ทธ๋จ์ ๊ตฌ์ฑํ๋ ๊ตฌ์ฑ์์์ ์ผ๋ถ
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋, ๋ด๊ฐ ์๊ฒ ์ชผ๊ฐ ๋์ ์ฝ๋๋ฅผ ์ฌ์ฌ์ฉํ๊ณ ์ถ์ ๋ ์ด๋ค
- export,default
โ๏ธmodule.html
<!DOCTYPE html>
<html lang="ko">
<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>
</head>
<body>
<h1>modules</h1>
<button>say</button>
<script>
document.querySelector('button').addEventListener('click', () => { say("๋ง๊ณ ") })
function say(user) {
alert(`'hello',${user}`)
}
</script>
</body>
</html>
์ผ๋ฐ html ๋ฌธ์์์ฑํ ๋ชจ๋ํ ํ๋ค
โ๏ธsay.js
/*export ๋ฅผ ๋ณ์๋ ํจ์ ์์ ๋ถ์ด๋ฉด ์ธ๋ถ ๋ชจ๋์์ ํด๋น ๋ณ์๋ ํจ์์ ์ ๊ทผ๊ฐ๋ฅ*/
export function say(user){
alert(`Hello,${user}!`)
}
โ๏ธmodule.html
...
<body>
<script type="module">
/* import ๋ฅผ ์ฌ์ฉํด say.js์ ํจ์ say๋ฅผ ์ฌ์ฉ */
import {say} from './say.js';
document.querySelector('button').addEventListener('click', () => { say("๋ง๊ณ ") })
</script>
</body>
</html>
์คํํ๋ฉด

Info: ๐ข ์ฃผ์์ฌํญ : ๋ผ์ด๋ธ์๋ฒ์์ ํ ๊ฒ
- ๋ชจ๋์ ๋ก์ปฌ ํ์ผ์์ ๋์ํ์ง ์๊ณ , HTTP ๋๋ HTTPS ํ๋กํ ์ฝ์ ํตํด์๋ง ๋์ํฉ๋๋ค.
- ๋ชจ๋์ ์์ ๋ง์ ์ค์ฝํ๊ฐ ์์ต๋๋ค. ๋ฐ๋ผ์ ๋ชจ๋ ๋ด๋ถ์์ ์ ์ํ ๋ณ์๋ ํจ์๋ ๋ค๋ฅธ ์คํฌ๋ฆฝํธ์์ ์ ๊ทผํ ์ ์์ต๋๋ค. ๋ธ๋ผ์ฐ์ ํ๊ฒฝ์์๋ย
<script type="module">
์ ์ฌ์ฉํด ๋ชจ๋์ ๋ง๋ค๋ฉด ๋ ๋ฆฝ์ ์ธ ์ค์ฝํ๊ฐ ๋ง๋ค์ด์ง๋๋ค. - ๋์ผํ ๋ชจ๋์ด ์ฌ๋ฌ ๊ณณ์์ ์ฌ์ฉ๋๋๋ผ๋ ๋ชจ๋์ ์ต์ด ํธ์ถ ์ ๋จ ํ ๋ฒ๋ง ์คํ๋ฉ๋๋ค. ์คํ ํ ๊ฒฐ๊ณผ๋ ์ด ๋ชจ๋์ ๊ฐ์ ธ๊ฐ๋ ค๋ ๋ชจ๋ ๋ชจ๋์ ๋ด๋ณด๋ด ์ง๋๋ค.
[์ฌ๋ฌ ๊ฐ์ฒด export & import ํ๊ธฐ]
โ๏ธmain.js
function funcA() {
console.log("functionAA");
}
function funcB(test) {
console.log(test, "functionbb");
}
const varC = "hello";
export { funcA, funcB, varC };
import ํ ๋๋ {} ๋ฅผ ์ด์ฉํฉ๋๋ค.
โ๏ธmodule.html
<script type="module">
import {funcA,funcB,varC} from './main.js';
funcA()
funcB(varC)
</script>
์คํํ๋ฉด

default export์ named export ์ฐจ์ด์
1. Default Export
- default ๋ก ์ ์ธ๋ ๋ชจ๋์ ํ๋์ ํ์ผ์์ ๋จ ํ๋์ ๋ณ์ ๋๋ ํด๋์ค ๋ฑ๋ง export ํ ์ ์๋ค.
//app.js
const app= () => {
...
}export default app
- import ํ ๋๋ ์๋ฌด ์ด๋ฆ์ผ๋ก๋ import ๊ฐ๋ฅํ๋ค.
//app-child1.js
import ypp from '../app'
๋๋
//app-child2.js
import bpp from '../app'
์ด๋ ๊ฒ ์ฌ์ฉํ๋๊ฒ์ด ๊ฐ๋ฅ
2. named export
- ํ ํ์ผ ๋ด์์ ์ฌ๋ฌ ๋ณ์/ํด๋์ค ๋ฑ๋ฑ์ export ํ๋ ๊ฒ์ด ๊ฐ๋ฅํ๋ค.
export class MyFirstClass { /* ... */ }
export class MySecondClass { /* ... */ }
- ๋ค๋ง, import ์ {} ์์๋ค๊ฐ export ๋ ์ด๋ฆ๊ณผ ๋์ผํ๊ฒ ์ค์ ํด์ผ ํ๋ค.
import { MyFirstClass, MySecondClass } from './MyClass'
- ๋ค๋ฅธ ์ด๋ฆ์ผ๋ก import ํ ์ ์์ผ๋ ์๋์ฒ๋ผย
as๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค.
import { MyFirstClass as BlahBlahClass, MySecondClass } from './MyClass'
asย ๋ฅผ ์ฌ์ฉํ๋ฉด ํ ํ์ผ์ ์๋ ํด๋์ค/๋ณ์๋ค์ ํ ๋ฒ์ import ํ ์ ์๋ค.
import * as Hello from './MyClass'
// ์ด๋ ๊ฒ import ํ๋ฉด Hello.MyFirstClass ์ด๋ฐ์์ผ๋ก ์ฌ์ฉํด์ผ ํจ