【Vue3.x】Create Project + Env

71 阅读1分钟

官方文檔: cn.vuejs.org/guide/intro…

1. Create Project

1.創建項目
  npm create vue@latest

2.安裝包
  npm install

3.啟動
  npm run dev

image.png

2. Technology

Vue3.x + Vite + Pinia + Router + ElementPlux +I18n + axios + TypeScript

  "dependencies": {
    "@element-plus/icons-vue": "^2.3.1",
    "axios": "^1.7.0",
    "element-plus": "^2.7.3",
    "moment": "^2.24.0",
    "pinia": "^2.1.7",
    "pinia-plugin-persist": "^1.0.0",
    "pinia-plugin-persistedstate": "^3.2.1",
    "vue": "^3.4.21",
    "vue-i18n": "^9.5.0",
    "vue-router": "^4.3.0"
  },

3. Package

3.1 Constructure

vue-demo
├── public/          # static files
│   └── favicon.ico  # title icon (可以多個,切換路由titile也切換) 
├── src/             # project root
│   ├── assets/      # images, icons, etc.靜態資源
│   ├── components/  # common components - 客製化頁面
│   ├── layouts/     # layout containers -header, footer,sidebar, etc.
│   ├── scss/        # scss styles
│   ├── config/      # 封裝http
│   ├── i18n/        # 多語言切換
│   │   ├── locales/        # 多語言切換
│   │   │   ├── en.ts         # 中文
│   │   │   ├── zh.ts         # 英文
│   │   │   └── xxx.ts        # 其他文
│   │   └── index.ts        # I18N切換
│   ├── router/       # routes config
│   ├── stores/      # template state example 
│   ├── views/pages  # Route apge,路由導航的頁面
│   ├── App.vue      # 三個標籤 template /script  /style
│   └── main.ts      # 加載所有組件,掛載都index.html
│
├── .env.development  # 多環境配置,在package.json啟動腳本中設定讀取
├── .env.production  # 多環境配置,在package.json啟動腳本中設定讀取
├── env.d.ts         # vue識別所有格式的文件
├── index.html       # 入口文件,main.ts
├── package.json     # dependency
└── vite.config.ts   # project config,install plugin,proxy

3.2 env

Notices:

  • 環境文件必須放到項目的根目錄下,vite才能正確識別
  • 文件必須以.env為前綴.env.development .env.product .env.test
  • 使用vite --mode development 來加載.env.development文件

.env.development

# 指定构建模式
VITE_NODE_ENV=development
 
# 页面 title 前缀
VITE_APP_TITLE=开发环境
 
# 网络请求公用地址
VITE_API_BASE_URL='https://api.uomg.com/api'

.env.production

# 指定构建模式 production
VITE_NODE_ENV=production
 
# 页面 title 前缀
VITE_APP_TITLE=生产环境
 
# 网络请求公用地址
VITE_API_BASE_URL='https://api.uomg.com/api'

3.3 package.json

  "scripts": {
    "dev": "vite --mode production --port 3000",
    "build": "run-p type-check \"build-only {@}\" --",
    "preview": "vite preview",
    "build-only": "vite build",
    "type-check": "vue-tsc --build --force",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
    "format": "prettier --write src/"
  },

3.4 package.json

1.直接打印
  console.log(import.meta.env)

2.後續封裝http的時候直接拿
  baseURL: import.meta.env.VITE_API_BASE_URL,

4. cross-env

另一種環境變量的配置方法

image.png