如何在 vite.config.js 中使用 Vite 环境变量? [英] How can I use Vite env variables in vite.config.js?

查看:128
本文介绍了如何在 vite.config.js 中使用 Vite 环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Vite 项目中使用以下 .env:

With the following .env in my Vite project:

# To prevent accidentally leaking env variables to the client, only
# variables prefixed with VITE_ are exposed to your Vite-processed code

VITE_NAME=Wheatgrass
VITE_PORT=8080

如何在我的 vite.config.js 中使用 VITE_PORT?

How can I use VITE_PORT in my vite.config.js?

推荐答案

您可以加载 app level 环境变量并将它们添加到 Node level 环境变量中:

You can load the app level env variables and add them to the Node level env variables:

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';


export default ({ mode }) => {
    process.env = {...process.env, ...loadEnv(mode, process.cwd())};

    // import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
    // import.meta.env.VITE_PORT available here with: process.env.VITE_PORT

    return defineConfig({
        plugins: [vue()],

        server: {
            port: process.env.VITE_PORT,
        },
    });
}

这篇关于如何在 vite.config.js 中使用 Vite 环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆