이번 블로그의 환경설정은 다음 블로그를 참고하여 작성되었습니다.
문제점
import Button from '../../components/Button'
React 혹은 Vue를 설치한 직후, 위 코드처럼 상대경로( ../)로 표현합니다.
상대경로에 대하여 간단히 설명하면 다음과 같습니다.
| 기호 | 의미 |
|---|---|
| / | root |
| ./ | 현재 위치 |
| ../ | 상위 경로 |
상대경로를 사용하면 프로젝트 빌드 시 여러 문제가 발생할 수 있습니다. 예를 들어, 이미지 로딩 실패 오류가 상대경로 설정 문제에서 비롯될 수 있습니다. 하지만 절대경로를 그대로 사용하기에는 경로가 너무 길어 불편합니다. 이러한 문제를 해결하기 위해 alias을 설정하여 간결하고 안정적인 경로 작성을 할 수 있습니다.
// Before
import Button from '../../components/Button'
// After
import Button from '@/components/Button'
위와 같이 @를 설정하면 절대경로를 사용하면서 깔끔하게 코드 작성 가능합니다.
01. Node.js 타입 선언 설치
yarn add -D @types/node
npm으로 설치
npm install --save-dev @types/node
02. vite.config.ts에 경로 alias 설정
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
})
여기서 path.resolve(__dirname, './src)가 프로젝트 src 폴더를 @로 가리키도록 설정합니다.
03. tsconfig.json에 node 타입 추가
{
"compilerOptions": {
"types": ["node"],
"moduleResolution": "node",
"esModuleInterop": true
}
}
위 코드를 추가해줍니다.
04. tsconfig.node.json 설정
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "node",
"target": "ESNext",
"types": ["node"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["vite.config.ts"]
}
05. 적용하기
위와 같이 환경설정 후, 이제 경로설정을 다음과 같이 수정하여 사용하면 됩니다.
// Before
import Button from '../../components/Button'
// After
import Button from '@/components/Button'