자바스크립트가 만들어진 지 얼마 안 되었을 때는 자바스크립트로 만든 스크립트의 크기도 작고 기능도 단순했기 때문에 자바스크립트는 긴 세월 동안 *모듈 관련 표준 문법 없이 성장해왔다. 하지만 최근 앱의 사이즈가 커지면서 모듈화의 필요성이 생겨났고 브라우저, 노드 진영에서도 모듈시스템을 도입하기 시작했다.
*모듈(module) : 분리된 파일 각각을 '모듈(module)'이라고 부르는데, 모듈은 대개 클래스 하나 혹은 특정한 목적을 가진 복수의 함수로 구성된 라이브러리 하나로 구성됩니다.
1. Next.js에서의 모듈
따로 특별한 설정을 해주지 않아도 모듈시스템이 적용되어 있다.
따로 설정이 없다면 이런식으로 ../../ 으로 구성된 상대경로로 적용된다. 상대경로로 표시하는 것이 문제되는 것은 아니지만 한눈에 보기에 알아보기가 쉽지가 않다.
타인이 코드의 전체적인 흐름을 파악할 때 처음에 보는 것이 import 문이기 때문에 유지보수에 영향을 미칠 수 있다.
2. 절대경로 변경(baseUrl)
가독성이 좋지 않기 때문에 alias 기능을 통해서 절대경로로 표시하는 것을 추천한다. 프로젝트에서 타입스크립트를 사용하고 있다면 쉽게 설정할 수 있다.
tsconfig.json 파일을 열어서 다음과 같이 수정해준다.
{
"compilerOptions": {
"baseUrl": ".",
},
...
}
위와 같이 compilerOptions에 baseUrl을 "."으로 설정하면 기본 경로를 프로젝트 최상단으로 설정하겠다는 말이다.
baseUrl 설정만으로도 많이 깔끔해졌다.
3. 절대경로(alias)
baseUrl 설정만으로도 괜찮지만, 모든 경로의 시작점이 동일하여 가장 최상의 경로인 src가 항상 표시되어 경로가 너무 길어진다.
좀 더 가독성을 좋게 하기 위해서는 alias 기능을 사용해 볼 수 있다.
다시 tsconfig.json파일을 열어서 다음과 같이 설정해준다.
@문자를 붙여주어 어디에서 불러온 파일인지 명확하게 명시하였다.
모든 파일의 경로가 src부터 시작하는 것이 아니라 각각 다른 경로의 폴더로 부터 시작되기 때문에 어디서 불러온 파일인지 명확하게 판단할 수 있다.