폴더의 depth가 깊어질수록 import시에 경로를 작성하는데 매우 귀찮고 코드도 깔끔해보이지 않다. 그럴때 Alias 설정을 해 간결하게 작성할 수 있다.
//bad
import Button from "../../../Common/Button";
//good
import Button from "@/Common/Button";Alias설정
우선 tsconfig.json에 compilerOptions에 path를 지정한다.
tsconfig.json
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
}
}
}Module resolver 설치와 babelrc 설정
지금 현재 프로젝트는 js와 ts가 혼재되어있기 때문에 tsconfig에만 설정하면 js에서는 불러오지 못하는 이슈가 있어 babel module resolver를 설치해주었다.
yarn add --dev babel-plugin-module-resolver
설치 후, .babelrc에 설정을 추가한다.
.babelrc
{
...
"plugins": [
[
"module-resolver",
{
"root": ["./"],
"alias": {
"@": "./src/"
}
}
]
]
}문제
여기까지 설정했는데 ts파일에서는 Alias가 제대로 적용이 되었으나 js에서는 import시 자동완성이 되지 않는 문제가 발생했다.
해결을 위해 jsconfig.json를 만들고 설정해주기로 했다.
jsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
"allowSyntheticDefaultImports": true
},
"exclude": ["node_modules"],
"include": ["**/*.js", "**/*.jsx"]
}하지만 여전히 해결이 되지 않았다.
알고보니 jsconfig와 tsconfig를 같이 사용할때는 필연적으로 하나의 config만 본다는 사실을 알게되었다. (해당이슈 : https://github.com/microsoft/TypeScript/issues/15869)
현재 js파일이 tsconfig를 보고 있으니 tsconfig에 includes에
.js, jsx를 추가해주자!
tsconfig include 설정
"include": [
"**/*.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.js",
"**/*.jsx"
]js, jsx를 추가해주었더니 ts, js파일에서 모두 import시 자동완성을 사용할 수 있었다.