Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

얼렁뚱땅개발로그^__^

[ React.js ] vite + typescript 프로젝트 절대경로 설정 본문

React.js

[ React.js ] vite + typescript 프로젝트 절대경로 설정

나니로그 2023. 12. 26. 16:42

vite로 리액트 프로젝트를 생성하고, import 하는 과정에서 상대경로로 import를 하니 코드가 길어지고 불편함을 느껴서 절대경로로 (import '@styles/main.scss') 설정하는 방법을 찾아보았다.

 

craco를 설치해서 절대 경로를 설정할 수 있다고 하여 npm install로 설치하는 과정부터 애먹고 있던 와중에 vite + typescript로 프로젝트르를 생성한 경우에는 craco를 따로 install 하지 않아도 된다는 블로그를 발견했다. 

 

tsconfig.json 과 vite.config.ts 두 개의 파일의 내용을 수정하면 절대 경로를 사용할 수 있다고 나와있었다.

 

* tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
    ...
      "@styles/*": ["styles/*"]
    ...
    },
    "target": "ES2020",
    ....
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

 

* vite.config.ts

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  // 아래 내용 추가
  resolve: {
    alias: [
      { find: "@", replacement: path.resolve(__dirname, "src") },
      { find: "@pages", replacement: path.resolve(__dirname, "src/pages") },
      { find: "@styles", replacement: path.resolve(__dirname, "src/styles") }, // 절대경로 추가
    ],
  },
});

 

위의 내용과 같이 추가하면 간편하게 절대경로를 사용할 수 있다.

 

https://shape-coding.tistory.com/entry/Vite-TypeScript-Vite-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%ED%99%98%EA%B2%BD%EC%97%90%EC%84%9C-%EC%A0%88%EB%8C%80-%EA%B2%BD%EB%A1%9C-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0