Javascript

export로 내보내고, import로 가져오기

jennyiscoding 2022. 10. 2. 14:40

**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>