이 글은 Vite를 이용하여 생성한 리액트 프로젝트에서 상대 경로를 절대 경로로 대체하는 방법에 대해 소개한다. 상대 경로를 사용하든, 절대 경로를 사용하든 동작에는 문제가 없지만, 프로젝트의 규모가 커질수록 상대 경로의 깊이가 깊어지기 때문에 경로가 복잡해진다는 문제가 발생할 수 있다. 이러한 문제를 해결하기 위해 상대 경로를 절대 경로로 대체하는 방법에 대해 알아보고자 한다.
상대 경로를 절대 경로로 대체하기
tsconfig.json
파일과 vite.config.ts
파일을 수정하여 상대 경로를 절대 경로로 대체할 수 있다.
vite.config.ts 파일 수정
vite.config.ts
파일은 아무것도 수정하지 않았다면, 아래와 같이 구성되어 있다.
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});
여기에 아래와 같이 코드를 추가하여 수정한다.
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: [
{ find: "@", replacement: "/src" },
{ find: "@components", replacement: "/src/components" },
],
},
});
하나씩 의미를 살펴보면 다음과 같다.
@
는/src
경로로 대체한다.@components
는/src/components
경로로 대체한다.
다른 경로도 추가하고 싶으면 같은 양식으로 늘리면 된다.
{ find:"@{directory_name}", replacement: "{directory_path}" }
tsconfig.json 파일 수정
다음은 tsconfig.json
파일을 수정하면 된다. 아래의 내용을 추가한다.
...
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
...
이 내용을 추가하면 아래와 같이 파일의 내용이 변경된다.
{
"compilerOptions": {
...,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
vite.config.ts
파일에 다른 경로도 추가했다면, paths
부분에 같은 양식으로 경로를 추가하면 된다.
사용하기
위와 같이 설정한 후, 절대 경로로 파일을 import 할 때는 다음과 같이 사용하면 된다. components
폴더 내에 있는 Button
컴포넌트를 불러온다고 가정하면 다음과 같다.
import Button from "@components/button"
상대 경로 대신에 앞에서 설장한 절대 경로를 이용하여 사용하면 된다.
'Development > React' 카테고리의 다른 글
리액트 | 리액트에서 Firebase로 이메일&패스워드 로그인 구현 (0) | 2024.02.12 |
---|---|
리액트 | React Router를 이용한 페이지 이동 처리 (with. react-router-dom) (0) | 2024.02.04 |
리액트 | styled-components를 이용한 React 스타일링 (with. styled-reset) (0) | 2024.01.29 |
리액트 | Vite를 이용한 React 프로젝트 생성 (설치부터 프로젝트 생성까지) (0) | 2024.01.25 |
리액트 | 리액트 프로젝트 GitHub page로 배포하기 (0) | 2024.01.17 |