ash*_*887 2 javascript environment-variables reactjs vite vite-reactjs
如何在 vite.config.js 文件中添加 Vite React 项目的环境变量
我想在.env文件中添加proxy_url,并在部署时将其添加到环境中。请往下看吧!
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
const proxy_url = "http://localhost:5000/";
export default defineConfig({
plugins: [react()],
server: {
proxy: {
"/api": {
target: proxy_url,
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, ""),
},
},
},
});
Run Code Online (Sandbox Code Playgroud)
StackOverflow 上的一些博客和答案,但他们正在解决 Vue 的相同问题。这些在我的 Vite-React 项目中对我不起作用!
你可以这样使用它:
安装“cross-env”包并配置 vite
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
define: {
__APP_ENV__: env.APP_ENV,
},
// rest of Vite config
}
}
Run Code Online (Sandbox Code Playgroud)
要在您的代码中使用,您可以这样做:
import.meta.env.VariableName
Run Code Online (Sandbox Code Playgroud)
更新:根据Vite文档,环境变量应该以VITE_前缀开头才能知道
例如在 .env 文件中:
VITE_BASE_API_URL=http://localhost:5000
使用它:
import.meta.env.VITE_BASE_API_URL
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15588 次 |
| 最近记录: |