모듈은 코드를 더 작은 조각으로 나누기 위해 ES 2015에 도입되었습니다. 모듈에는 클래스나 함수가 포함될 수 있습니다. 키워드 내보내기 및 가져오기는 변수, 함수, 개체를 내보내고 다른 파일로 가져오는 데 사용됩니다.
참고 − 이 예제를 실행하려면 localhost 서버를 실행해야 합니다.
다음은 JavaScript의 모듈에 대한 코드입니다.
INDEX.html
예시
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color:blueviolet;
}
</style>
</head>
<body>
<h1>Modules in JavaScript</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>Click on the above button to import module</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html> 스크립트.js
import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
test();
}) 샘플.js
let resultEle = document.querySelector(".result");
export default function testImport(){
resultEle.innerHTML = 'Module testImport has been imported';
} 출력
'가져오기' 버튼 클릭 시 -
