Write the Code. Change the World.

7月 09

https://cn.vite.dev/guide/env-and-mode

在本地运行和打包使用不同的配置的时候,环境变量的配置就很有作用。比如本地运行调用接口用的域名是 https://test.xxx.com,正式上线调用的接口是 https://www.xxx.com

先创建智能提示

编辑 env.d.ts 文件,内容如下。

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

interface ImportMetaEnv {
  readonly VITE_API_BASE_URL: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

创建 env 文件

项目根目录添加 .env 文件。添加以下内容。

VITE_API_BASE_URL=https://test.xxx.com

项目根目录添加 .env.production 文件。添加以下内容。

VITE_API_BASE_URL=https://www.xxx.com

修改 ./src/home/index.vue 文件,测试

<template>
  <div>
    <h1>HI, {{ user.name }} , Welcome to the Home Page</h1>
    <h2>Email: {{ user.email }}</h2>
    <h2>Api: {{ api }}</h2>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

const user = ref<User>({
  id: 1,
  name: 'John Doe',
  email: 'john.doe@example.com',
  createdAt: new Date(),
})

const api = ref(import.meta.env.VITE_API_BASE_URL)

</script>

<style scoped>
h1 {
  color: #42b983;
  font-size: 2em;
}
</style>

测试环境

pnpm dev

生产环境

pnpm dev --mode production

结果如图:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注