vite에서 절대경로 설정하기

숭글·2023년 12월 21일
0

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "."
  },
  "includes": ["."]
}

일단 프로젝트 내 최상위 경로(jsconfig.json이 있는 위치)를 baseUrl로 설정한다.

번듈러로 webpack을 사용했을 때는 여기까지만 해도 절대경로로 모듈 임폴트하는 게 가능했지만
vite에서는 모듈을 찾을 수 없다고 에러가 발생하게 된다.

resolve.alias

vite.config.js파일을 수정해 절대경로로 모듈을 참조할 수 있도록했다. 별칭을 등록해두면 @rollup/plugin-alias의 entries옵션으로 전달돼 모듈을 찾을 수 있게 된다.

Object Format
The Object format allows specifying aliases as a key, and the corresponding value as the actual import value. For example:

alias({
  entries: {
    utils: '../../../utils',
    'batman-1.0.0': './joker-1.5.0'
  }
});

Array[...Object] Format
The Array[...Object] format allows specifying aliases as objects, which can be useful for complex key/value pairs.

entries: [
  { find: 'utils', replacement: '../../../utils' },
  { find: 'batman-1.0.0', replacement: './joker-1.5.0' }
];

위 예시처럼 오브젝트로 전달할 수도 있고 배열을 전달할 수도 있다.

vite.config.js

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      src: '/src',
      component: '/src/component',
    },
  },
});

위처럼 수정해 절대경로 모듈을 참조할 수 있게 설정했다!


사람들이 왜 절대경로를 쓸 때 경로 앞에 '@'를 넣는지 몰랐는데.. 설정하면서 알게됐다ㅜㅜ src를 루트로 지정하고싶었는데 그럼 : '\src'를 뜬금없이 넣어야하니... ㅋㅋㅋㅋㅋㅋㅋㅋ 작은 프로젝트라 일단 골뱅이는 안썼는데.. 나중엔 결국 써야할듯하다 🥹

profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

0개의 댓글