**export로 내보낼 때는 import 시 {}를 붙이고
export default로 내보낼 때는 import 시 {}를 붙이지 않는다.
1. export 만을 사용해서 변수를 내보내는 경우
greetings.js
export const hello = "hello"
index.js
import { hello } from "./greetings.js";
console.log(hello)
결과 :
주의사항 ) import해올 때 파일명.js를 붙인다!!
2. export default 로 함수를 내보내는 경우
greetings.js
export default function (){
console.log('nice to meet you')
}
index.js
import nice from './greetings.js';
nice()
결과
3. export로 변수 2개를 내보내는 경우
greetings.js
export const i = 'I'
export const am = "am"
index.js
import {i, am} from './greetings.js';
console.log(i, am)
4. export default로 함수 2개를 내보내는 경우
greeting.js
function king(){
console.log('king')
}
function oftheworld(){
console.log('oftheworld')
}
export default {king, oftheworld}
index.js
import greetings from './greetings.js';
greetings.king()
greetings.oftheworld()
index.html은 type="module"을 반드시 써야한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>자바스크립트 기초</title>
<script defer src="index.js" type="module"></script>
</head>
<body>
<button id="elem">클릭하세요.</button>
</body>
</html>
'Javascript' 카테고리의 다른 글
프로토타입 (0) | 2022.10.02 |
---|---|
여러개의 element를 공통된 TagName으로 가져온 후 addEventListener처리해보기 (0) | 2022.10.02 |
함수선언문과 함수표현식의 차이, 호이스팅 (0) | 2022.10.02 |
Javascript reduce사용법 (0) | 2022.10.02 |
객체안에 함수에서 변수를 접근할 경우 this를 붙여야한다 (0) | 2022.10.01 |