자바스크립트 코드가 길어지면 파일을 분리하여 관리하는 것이 좋은 관습입니다. ES6의 import/export 문법을 활용하면 파일 간에 필요한 변수, 함수, 혹은 클래스를 선택적으로 내보내거나(import/export) 가져올 수 있습니다. 단, import로 가져온 값은 읽기 전용임을 유의하세요.
<script> 태그에 type="module" 속성을 추가해야 합니다.<script type="module">
// ES6 모듈 문법 사용 가능
</script>
export default를 사용하면 한 파일에서 단 하나의 기본(default) 값을 내보낼 수 있습니다.
또한 import 시에는 임의의 변수명으로 가져올 수 있습니다.
(library.js)
var a = 10;
export default a;
(index.html)
<script type="module">
import a from './library.js';
console.log(a); // 출력: 10
</script>
library.js 파일에서 변수 a를 export default로 내보냅니다.index.html 파일의 모듈 스크립트에서 a라는 이름으로 import하여 사용할 수 있습니다.여러 변수를 한 번에 내보내고 싶다면 named export를 사용합니다.
(library.js)
var a = 10;
var b = 20;
export { a, b };
(index.html)
<script type="module">
import { a, b } from './library.js';
console.log(a); // 출력: 10
console.log(b); // 출력: 20
</script>
export { a, b } 구문을 사용해 여러 변수를 내보냅니다.{ } 안에 내보낸 변수명을 명시하여 가져옵니다.또한 export var a = 10;와 같이 내보내는 것도 가능합니다.
동일 파일에서 기본 export와 named export를 함께 사용할 수 있습니다.
(library.js)
var a = 10;
var b = 20;
var c = 30;
export { a, b };
export default c;
(index.html)
<script type="module">
import c, { a, b } from './library.js';
console.log(c); // 출력: 30
console.log(a); // 출력: 10
console.log(b); // 출력: 20
</script>
c는 import 시 맨 왼쪽에 위치시키고,{ } 내에 나열합니다.import할 때 as를 사용하여 변수명을 새롭게 지정할 수 있습니다.
(library.js)
var a = 10;
var c = 30;
export { a };
export default c;
(index.html)
<script type="module">
import c, { a as 폭발 } from './library.js';
console.log(폭발); // 출력: 10
console.log(c); // 출력: 30
</script>
a를 폭발이라는 별칭으로 import하여 사용할 수 있습니다.내보낸 변수가 많을 경우, * 기호를 사용하여 모든 named export를 하나의 객체로 묶어 가져올 수 있습니다.
(library.js)
var a = 10;
var b = 20;
var c = 30;
export { a, b };
export default c;
(index.html)
<script type="module">
import c, * as 변수모음 from './library.js';
console.log(변수모음.a); // 출력: 10
console.log(변수모음.b); // 출력: 20
console.log(c); // 출력: 30
</script>
as 변수모음은 library.js에서 내보낸 모든 named export를 변수모음 객체에 담아 import합니다.c)는 별도로 import하여 사용합니다.과거에는 require와 module.exports를 사용하여 모듈식 개발을 진행했습니다.
예를 들면:
(export 하는 파일)
module.exports.a = 10;
(import 하는 파일)
var 가져온거 = require('./library.js');
단, import/export 문법은 IE 등 일부 구형 브라우저에서 호환되지 않으므로, 일반 HTML/CSS/JS 프론트엔드 개발에서는 를 사용할 수 있습니다.
또는 모던 브라우저 환경에서는
<script type="module" src="경로"></script>를 사용하면 됩니다.
as 구문을 사용하여 모든 named export를 하나의 객체로 import 가능<script type="module"> 필수