Vite 安裝與環境變數設定

Vite 6安裝
node 20.15.1
gitHub上的說明(vite ^6.0.1”)

相容性說明

Vite6 出現Pwa loader 404。

必須安裝PWA漸進式參考gitHub上的說明

相容性說明

Vite 需要 Node.js 版本 18+。 20+。 但是,某些模板需要更高的 Node.js 版本才能運作,如果您的套件管理器發出警告,請升級。

這裡使用node版本 v18.12.1 ### 終端機安裝指令
1
npm create vite@latest 資料名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

? Project name: › vite-project //專案名稱
? Select a framework: › - Use arrow-keys. Return to submit.
Vanilla
❯ Vue
React
Preact
Lit
Svelte
Others
? Select a variant: › - Use arrow-keys. Return to submit.
JavaScript
❯ TypeScript
Customize with create-vue ↗
Nuxt ↗

參考官網
1
2
3
4
cd vite-project
npm install
npm run dev

安裝完成
gitHub上的說明

gitHub上的說明(vite ^5.1.0”)

環境變數設定

修改vite.config.js 檔案,加入以下

1
2
3
4
5
6
7
8
9
10
11
import { fileURLToPath, URL } from 'node:url';
import { resolve } from 'path';
export default defineConfig({
base: "/",
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
envDir: resolve(__dirname, './env'),
})

當從命令列執行 vite 時,Vite 會自動嘗試解析專案根目錄中名為 vite.config.js 的設定檔(也支援其他 JS 和 TS 擴充功能)。
最基本的設定檔如下所示:
官網說明
完整檔案

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
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from "node:url"
import { resolve } from "path"

export default defineConfig({
base: '/',
plugins: [
vue(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
// css 配置
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/base.scss";`
}
}
}
envDir: resolve(__dirname, './env'),
});

處理錯誤:修改vite.config.ts配置與安裝 @types/node

1
npm install --save-dev @types/node

**在專案內加入env資料夾資料夾內新增:.env.development,.env.production,.env.staging

開發端環境.env.development

1
VITE_API_URL = '開發端環境Api網址'

正式主機位置.env.production

1
VITE_API_URL = '正式主機位置Api網址'

測試環境.env.staging

1
2
# QA測試環境
VITE_API_URL = 'QA測試環境Api網址'

在頁面中使用環境變數
如果在開發中會得到開發中的變數,正式環境就得到正式環境中的變數,測試環境以此類推
環境變數的命名都大寫搭配底斜線如=>VITE_API_URL=’https://xxx.tw
使用import.meta.env.VITE_API_URL

1
import.meta.env.VITE_API_URL

gitHub上的說明-新增環境變數
gitHub上的說明 頁面的使用import.meta.env.VITE_API_BASIC_URL
環境變數

TypeScript 的智能提示

在 src 目錄下建立 env.d.ts
增加 ImportMetaEnv

1
2
3
4
5
6
7
8
9
10
/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_APP_TITLE: string
// 更多環境變量...
}

interface ImportMeta {
readonly env: ImportMetaEnv
}