자바스크립트 코드가 길어지면 다른 파일로 쪼개는 것이 좋은 관습이다.
(참고) import 해온 변수, 함수는 사용이 가능하지만 수정은 불가능하다.(read-only)예시)
index.html 파일과 library.js 파일이 있다.
library.js 파일에 있는 내용을 index.html의<script>
태그 내에 가져다 쓰려고 한다.(index.html) <script type = "module"> /*html 파일 안에서 ES6 import 문법을 쓰려면, script 태그 안에 type="module" 설정해야 함 */ </script>
(1) export default / import 를 쓰면 다른 파일에 있는 변수 등을 가져다 쓸 수 있다.
- JS 파일에서 특정 변수를 다른 파일에서 이용할 수 있도록 내보내고 싶다면, export default 변수명 이라고 쓰면 됨.
- 그 변수를 다른 파일에서 쓰려면, 다른 파일안에서 import 변수명 from 'js파일 경로' 쓰기 (import 뒤 변수명은 내 마음대로)
(library.js) var a = 10; export default a; ------------------------ (index.html) <script type="module"> import a from 'library.js'; console.log(a); </script>
(2) 여러개를 export 할 수 있다.
- JS파일에서 변수 여러개를 내보내고 싶다면 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); </script>
- 주의점
export {변수명1, 변수명2,...} 형식으로 담아야 함.
import {변수명1, 변수명2,...} 형식으로 가져와야 함.
또한, import 뒤 변수명을 마음대로 작명할 수 없고, export 한 변수명 그대로 써야 함.
(3) export와 export default 동시에 사용할 수 있음(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); </script>
import 할 때, export default 한 변수는 맨 왼쪽에, {} 중괄호 안의 export한 변수는 그 다음에 써주면 됨.
(4) as를 이용하여 변수명을 새로 짓기
import를 할 때, 변수명 오른쪽에 as 라는 키워드를 붙일 수 있다.
변수명 as 새 변수명<script type="module"> import c, {a as newKey} from 'library.js'; console.log(newKey); </script>
(5) import 할 때 변수가 너무 많다면 * 기호 사용
<script type="module"> import c, * as many from 'library.js'; console.log(many.a); console.log(c); </script>
'*' 이라는 기호는 export {} 한 변수들을 모두 import 해주세요 라는 뜻.
그러나 그냥 쓸 순 없고, as로 새로운 변수명을 지어줘야 함.
이렇게 되면, 새롭게 지은 변수명에 export {} 한 모든 변수들이 들어감.