[Vite] Vite 환경에서 path alias 설정하기

찐새·2023년 1월 9일
4

React

목록 보기
16/21
post-thumbnail

코드 리팩토링하다 상대 경로가 너무 지저분해서 tsconfigpaths를 수정했다.

{
  "compilerOptions": {
    // (...)
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"],
      "@components/*": ["components/*"],
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

눈으로 보기에는 문제가 없었다. 그러나 실행해 보니 다음과 같은 에러가 발생했다.

[vite] Internal server error: Failed to resolve import "@components/common" from "src\Router.tsx". Does the file exist?

찾아보니 vite는 config 파일을 통해 alias를 지원하니 그것을 이용하란다. (Vite issue 88 답변 중)

공식 문서와 여러 검색 결과를 참고해서 path alias를 설정했다.

vite.config.js

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [
      { find: "@", replacement: path.resolve(__dirname, "src") },
      {
        find: "@components",
        replacement: path.resolve(__dirname, "src/components"),
      },
    ],
  },
});

find에는 별칭을, replacement에는 절대 경로를 주입한다. 별칭이 있는 경로의 수만큼 alias 배열에 추가한다. 별칭은 tsconfig.jsonpaths와 일치시킨다.

진짜 코드만 보면 너무 간단한데 모르니까 엄청 해멨다. ㅠㅠ

그보다 간단한 버전도 있다.

vite-tsconfig-paths 플러그인

일일이 alias를 설정하지 않아도 tsconfigpaths를 적용시켜주는 플러그인이다.

npm install -D vite-tsconfig-paths으로 설치 후 vite.config.jsplugins에 추가한다.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import tsconfigPaths from "vite-tsconfig-paths";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), tsconfigPaths()],
});

참고
TypeScript - paths
Vite - resolve-alias
Setup path aliases w/ React + Vite + TS

profile
프론트엔드 개발자가 되고 싶다

2개의 댓글

comment-user-thumbnail
2023년 9월 26일

설정 도움받고 갑니다.

답글 달기
comment-user-thumbnail
2023년 11월 7일

감사합니다!

답글 달기