Vue环境变量

28 阅读1分钟

模式是 Vue CLI 项目中一个重要的概念。默认情况下,一个 Vue CLI 项目有三个模式:

  • development 模式用于 vue-cli-service serve
  • test 模式用于 vue-cli-service test:unit
  • production 模式用于 vue-cli-service build 和 vue-cli-service test:e2e
vue-cli-service build --mode development

你可以在你的项目根目录中放置下列文件来指定环境变量:

.env                # 在所有的环境中被载入
.env.local          # 在所有的环境中被载入,但会被 git 忽略
.env.[mode]         # 只在指定的模式中被载入
.env.[mode].local   # 只在指定的模式中被载入,但会被 git 忽略

使用

只有以 VUE_APP_ 开头的变量会被 webpack.DefinePlugin 静态嵌入到客户端侧的包中。你可以在应用的代码中这样访问它们:

console.log(process.env.VUE_APP_SECRET)

TS

Package

"scripts": {
  "dev": "vite --mode development", // --mode development可以省略,运行 npm run dev 自动指定
  "build": "vue-tsc --noEmit && vite build --mode production", // --mode production可以省略,运行 npm run build 自动指定
  "preview": "vite preview"
},

import.meta.env.MODE: {string} 应用运行的模式
import.meta.env.BASE_URL: {string} 部署应用时的基本 URL
import.meta.env.PROD: {boolean} 应用是否运行在生产环境
import.meta.env.DEV: {boolean} 应用是否运行在开发环境 (永远与 import.meta.env.PROD相反)

应用级环境变量

.env.developlent

VITE_API_URL=/api/
VITE_LOCATION_ORIGIN=http://localhost:3000/

另外自定义的环境变量,还需要在 env.d.ts 中声明变量类型

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_TITLE: string
  readonly VITE_API_URL: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
  const component: DefineComponent<{}, {}, any>
  export default component
}

Vite把环境变量通过 import.meta.env 暴露出来,在 .vue 中使用方式如下

<script setup lang="ts">
  console.log(import.meta.env)
</script>

Proxy真实地址

bypass(req, res, options ) {
  const proxyURL = options.target + req.url
  console.log('proxyURL', proxyURL)
},