> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/centos/vue/vite-jie-jue-kai-fa-sheng-chan-fu-wu-qi-de-zi-dong-qie-huan.md).

# Vite解决开发、生产服务器的自动切换

如果每次都是手动去来回切换，很容易因为认为的疏忽造成事故，所以很多时候还是希望可以根据项目的状态，自动来切换请求的服务器是开发服还是生产服。

`vite`提供了`.env文件`，这个文件是环境变量问题，默认提供了四种文件格式

```js
    .env               # 所有情况下都会加载
    .env.local         # 所有情况下都会加载，但会被 git 忽略
    .env.[mode]        # 只在指定模式下加载
    .env.[mode].local  # 只在指定模式下加载，但会被 git 忽略
```

其中我们可以使用`.env[mode]`的格式可以在**不同模式下加载不同内容**。

* 在根目录新建`.env.development`文件，表示开发时的`.env`文件

```js
# .env.development

VITE_BASE_API = '/api'
```

* 在根目录新建`.env.production`文件，表示线上环境时的`.env`文件

```js
# .env.production

VITE_BASE_API = '/v1-api'
```

**注意：`vite`里面默认只有`VITE_`为前缀的变量才会暴漏出去给`vite`进行处理，所以变量应该是以`VITE_`开头**

## 验证

* 在`request.js`里面进行如下增加

```js
import axios from 'axios'

// 新增了下面这条，让他输出当前的地址，可以在浏览器console中进行查看
console.log(import.meta.env.VITE_BASE_API)

const service = axios.create({
  // 根据项目的状态，自动切换请求的服务地址
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 5000,

})

 export default service
    
```

* 线上环境测试

执行`npm run build`，先对项目进行打包。然后`cd dist` 运行`anywhere`（如果没安装的话，可以运行`npm install anywhere -g`）,在去浏览器`console`中查看即可。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/centos/vue/vite-jie-jue-kai-fa-sheng-chan-fu-wu-qi-de-zi-dong-qie-huan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
