[TypeScript] 모듈 임포트 절대경로 설정, 자동완성 (tsconfig, VScode)
import MyComponent from "../../../../../components/MyComponent";
import ADifferentFile from "../../../some/other/dir/ADifferentFile";
import PageMeta from "@components/PageMeta";
import RecentPostList from "@components/RecentPostList";
import SocialCards from "@components/SocialCards";
1. tsconfig 설정
{
"compilerOptions": {
...
"paths": {
"@/*": ["./src/*"]
},
...
}
}
tsconfig의 컴파일러 옵션에서 path 옵션을 설정해줍니다.
src/
├── api
├── components
│ ├── buttons
│ ├── cards
│ ├── group
│ ├── modals
│ ├── ui
│ └── utils
├── lib
├── pages
├── styles
└── types
프로젝트 구조가 위와 같다고 하면, 아래와 같이 절대경로 임포트가 가능합니다.
import ProfilePic from "@/components/ProfilePic";
import { User } from "@/types/User";
import { useCheckedUsersStore } from "@/lib/stores";
좋습니다! 하지만 VScode를 사용할 때 자동완성 기능을 많이 사용하고는 합니다.
기본적으로 모듈 임포트 자동완성 옵션은 가장 짧은 경우를 선택하기에 상대경로 포맷으로 임포트 되곤 합니다.
아예 자동완성도 절대 경로를 사용하게끔 해볼까요?
2. VScode 모듈 임포트 자동완성 절대경로 설정
Workspace 설정에 들어가 importModule을 검색하면 아래와 같이 나옵니다.
참고한 글들
Tell VS Code to always use relative paths for TypeScript auto imports?
VS Code is auto-importing everything relative to baseUrl using Node-like non-relative paths, which is what I don't want. How do I tell VS Code to import everything with relative paths (except for ...
stackoverflow.com
Cannot find module '@components/...' or its corresponding type declarations.ts(2307) in React Native
Previously have used TypeScript with React several times without any issues. Moving over to React Native and recieved this error for both imports for my custom "RoundedButton" and "C...
stackoverflow.com