공부/JS

[JS정리]Import 간단 사용 법

캄성 2022. 7. 21. 17:43

JasvaScript 모듈 사용 방법

import 와 export를 사용하여, script src 구문의 반복 사용을 줄이는 등의 용도로 사용 한다.

 

사용 방법 예제

일반적인 사용 - Module 비 사용

HTML

<!DOCTYPE html>
<head>
    <title>Document</title>
</head>
<body>
    <script src="hello.js"></script>    
    <script src="main.js"></script>
</body>
</html>

JS 1 - main.js

hello1();

JS 2 - hello.js

function hello1(){
    console.log('Hello1!');   
}

 

Import 를 사용한 사용 법 - 1 한개의 함수를 불러 올 경우

= HTML

<!DOCTYPE html>
<html lang="en">
<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>
    <script type="module" src="main.js"></script>    
</body>
</html>

 = JS 1 - main.js

import { hello1 } from './hello.js';
hello1();

= JS 2 - hello.js

export function hello1(){
    console.log('Hello1!');   
}

 

Import 를 사용한 사용 법 - 2개의 함수를 불러 올 경우

= JS 1 - main.js

- 각 함 수 별로, 임포트 하는 방법

import { hello1 } from './hello.js';
import { hello2 } from './hello.js';

hello1();
hello2();

- 하나의 임포트에 2개의 함수를 불러 오는 방법

import { hello1, hello2 } from './hello.js';

hello1();
hello2();

- 문전체를 표기하여 불러 온 후 함수를 재 지정하는 방법

import * as hello from './hello.js';

hello.hello1();
hello.hello2();

= JS 2 - hello.js

- export 할 함수를 하나씩 지정하는 방법

export function hello1(){
    console.log('Hello1!');   
}


export function hello1(){
    console.log('Hello1!');   
}

- export할 함수를 한번에 설정하는 방법

 function hello1(){
    console.log('Hello1!');   
}


 function hello2(){
    console.log('Hello1!');   
}

export {hello1,hello2 }