JavaScript 모듈 시스템에서 import as와 export as 구문은 코드의 가독성과 유연성을 높여주는 강력한 기능입니다.
import as란?
import as를 사용하면 가져오는(named) 모듈을 원하는 다른 이름으로 불러올 수 있습니다. 예를 들어, 원본 함수 이름이 길거나 의미가 명확하지 않을 때 더 직관적인 이름으로 변경하여 사용할 수 있습니다.
export as란?
export as는 반대로 내보내는 모듈을 다른 이름으로 내보낼 수 있게 해줍니다. 이를 통해 외부에 공개되는 이름을 자유롭게 지정할 수 있습니다.
예제 코드
다음은 JavaScript에서 import as와 export as 구문을 활용한 전체 예제입니다.
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: rebeccapurple;
}
</style>
</head>
<body>
<h1>Import as and Export as in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>위 버튼을 클릭하면 가져온(imported) 함수가 실행됩니다.</h3>
<script src="script.js" type="module"></script>
</body>
</html>script.js
import {test, tellTime as showTime} from "./sample.js";
let resultEle = document.querySelector('.result');
document.querySelector('.Btn').addEventListener('click',()=>{
resultEle.innerHTML+=test();
resultEle.innerHTML+=showTime();
})위 코드에서 tellTime 함수를 showTime이라는 새로운 이름으로 가져오고 있는 것을 확인할 수 있습니다. 이것이 바로 import as 구문의 역할입니다.
sample.js
function testImport() {
return "Module testImport has been imported" + "";
}
function tellTime() {
return new Date();
}
export { testImport as test, tellTime };반대로 sample.js 파일에서는 testImport 함수를 test라는 이름으로 내보내고 있습니다. 이것이 export as 구문의 활용 예시입니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

'CLICK HERE' 버튼을 클릭하면 아래와 같이 결과가 표시됩니다.

버튼을 클릭하면 test() 함수가 반환한 문자열과 showTime()(원래 tellTime) 함수가 반환한 현재 날짜와 시간이 화면에 함께 출력되는 것을 확인할 수 있습니다.
정리
import as와 export as 구문을 활용하면 모듈의 이름을 자유롭게 변경하여 사용할 수 있어, 코드 충돌을 방지하고 더 읽기 쉬운 코드를 작성하는 데 큰 도움이 됩니다.