如何在 vite.config.js 中使用 Vite 环境变量?

How can I use Vite env variables in vite.config.js?

在我的Vite项目中有如下.env

# 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

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

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,
        },
    });
}