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

2

Web

목록 보기
2/5

프로젝트의 상대 경로가 너무 지저분해 보여서 path alias 를 설정해주려고 한다.

1. vite-tsconfig-paths 플러그인 설치

tsconfig의 paths를 적용시켜주는 플러그인

$ yarn add -D vite-tsconfig-paths

2. vite.config.js 수정

TypeScript를 Vite와 함께 사용할 때 TypeScript의 모듈을 확인하는 동작이 tsconfig.json의 baseUrl 및 paths 구성에 의존하는데, ESLint는 기본적으로 이 구성을 읽지 않는다.

ESLint가 프로젝트의 모듈 경로를 올바르게 확인하도록 하려면 Vite 구성 파일에서 vite-tsconfig-paths 플러그인을 사용할 수 있다. 이 플러그인은 tsconfig.json에서 baseUrl 및 paths 구성을 읽고 ESLint에서 사용할 수 있도록 한다.

또한, 프로젝트의 모듈 경로를 올바르게 확인할 수 있으므로 오류를 방지하고 코드를 올바르게 분석할 수 있다.

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()],
});

+) 이렇게 설정하면 첫줄에 redline이 생기면서 다음과 같은 에러 메세지가 뜬다.

Parsing error: ESLint was configured to run on `<tsconfigRootDir>/vite.config.ts` using `parserOptions.project`: /users/rohyoungji/documents/git-repo/moit-web/tsconfig.json
However, that TSConfig does not include this file. Either:
- Change ESLint's list of included files to not include this file
- Change that TSConfig to include this file
- Create a new TSConfig that includes this file and include it in your parserOptions.project
See the typescript-eslint docs for more info: https://typescript-eslint.io/linting/troubleshooting#i-get-errors-telling-me-eslint-was-configured-to-run--however-that-tsconfig-does-not--none-of-those-tsconfigs-include-this-fileeslint

그래서 하라는대로 eslint 설정에 다음과 같이 vite.config.ts를 추가해주었고, 에러 사라짐!

3. tsconfig.json 수정

이제 우리가 원하는 path를 complier option에 추가해주면 된다!

{
  "compilerOptions": {
    "baseUrl": "./src",
  },

이렇게 하고 상대 경로로 바꿔보면 잘 동작하는 것을 확인할 수 있다.

profile
𝙸 𝚊𝚖 𝚊 𝗙𝗘 𝚍𝚎𝚟𝚎𝚕𝚘𝚙𝚎𝚛 𝚠𝚑𝚘 𝚕𝚘𝚟𝚎𝚜 𝗼𝘁𝘁𝗲𝗿. 🦦💛

0개의 댓글