프로젝트를 진행할 때 다른 컴포넌트를 가져오거나 로컬 이미지 파일을 사용하는 등 파일 외부에 위치한 자원을 사용하고자 할 때 import
구문을 사용한다.
// 상대경로
import Profile from "../../../components/user/profile";
// 절대경로
import Profile from "components/user/profile";
프로젝트 규모가 커져 폴더 구조가 깊어지게 되면 결국 상대경로에 지옥에 빠지게 되어 가독성을 해치게 된다. 상대경로는 절대경로에 비해 비교적 빠르다는 장점이 있지만 코드의 가독성을 위해서 프로젝트 진행 시 무조건 절대경로 설정을 해주고 있다.
프로젝트 최상단 루트에 jsconfig.json
파일을 추가하고 아래 코드를 작성
(TS 환경일경우 tsconfig.json
)
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
baseUrl
절대경로를 사용할 때 기준이 되는 경로를 설정하는 속성이다. jsconfig.json
파일이 위치한 경로를 말하며 보통 src
폴더 내부에서 파일들을 생성하므로 src
로 설정한다.
include
import
구문을 사용할 때 src
를 포함할지에 대한 여부이다.
// include에 src 미포함
import Profile from "src/components/user/profile";
// include에 src 포함
import Profile from "components/user/profile";