본문 바로가기

개발/Vue

[Vite] webpack에서 vite로 전환하기

Webpack에서 더 빠르고 간편한 Vite로 전환한 기록


 

Vite로 전환하는 방법 두가지

1. 기존 프로젝트를 수정하여 Vite로 전환하기
2. 신규 프로젝트를 Vite로 생성하고 기존 소스를 이동하기

 

1. 기존 프로젝트를 수정하여 Vite로 전환하기

vite 라이브러리 설치

$ npm install vite @vitejs/plugin-vue --save-dev

 

vite.config.js 파일 생성

// vite.config.js
import { fileURLToPath, URL } from 'node:url';

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: { // 기본 디렉토리 정의
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  define: { // 환경변수 정의
    'process.env': process.env,
  },
  server: { // 개발 서버 포트 설정
    port: 7600,
  },
});

 

index.html 수정

  • /public 경로에 있던 index.html을 root 로 이동
  • 파일 수정
// index.html

// 1. BASE_URL 참조 제거
// 기존
<link rel="icon" href="<%= BASE_URL %>favicon.ico" />
// vite
<link rel="icon" href="/favicon.ico" />

// 2. entrypoint 추가
 <script type="module" src="/src/main.js"></script>

 

vue-cli dependency 삭제

  • vue-cli용 dependency
    • @vue/cli-plugin-babel
    • @vue/cli-plugin-eslint
    • @vue/cli-service
  • webpack 설정 dependency
    • copy-webpack-plugin → vite-plugin-static-copy로 변경
$ npm uninstall @vue/cli-plugin-babel @vue/cli-plugin-eslint @vue/cli-service copy-webpack-plugin --save

 

package.json 

  • build script 업데이트
// package.json
  "scripts": {
		// 기존
    "serve": "vue-cli-service serve",
    "build-dev": "vue-cli-service build --mode development",
    "build-real": "vue-cli-service build --mode production",
		// vite
    "dev": "vite --host",
    "build-dev": "NODE_ENV=DEV vite build --mode=development",
    "build-real": "NODE_ENV=production vite build --mode=production",
    "preview": "vite preview"
  },


2. 신규 프로젝트를 Vite로 생성하고 기존 소스를 이동하기

프로젝트 생성

// vite 프로젝트 설치 -> 프레임워크 vue 선택
$ npm create vite@latest

// 또는 vue 프로젝트 설치 (기본 빌드 도구 vite)
$ npm create vue@latest

// 실행
$ cd "프로젝트 명"
$ npm install
$ npm run dev

 

소스 수정

 

.env 파일

  • VITE_ 접두사를 붙여준다.
  • import.meta.env  객체를 통해 문자열 형태로 접근이 가능하다.
// .env
VITE_GA_KEY=

 

import vue 파일

  • .vue extension을 추가하며 이동

 

tilde 제거

// ex
// before
@import "~bootstrap/scss/bootstrap"
// after
@import "bootstrap/scss/bootstrap"

 

 


참고

A Guide to Migrating from Webpack to Vite

vite 공식 문서

How to Migrate from Vue CLI to Vite