diff --git a/packages/vite/src/node/env.ts b/packages/vite/src/node/env.ts index 374e1f049c0618..5c1994288c6f98 100644 --- a/packages/vite/src/node/env.ts +++ b/packages/vite/src/node/env.ts @@ -5,6 +5,15 @@ import { expand } from 'dotenv-expand' import { arraify, tryStatSync } from './utils' import type { UserConfig } from './config' +export function getEnvFilesForMode(mode: string): string[] { + return [ + /** default file */ `.env`, + /** local file */ `.env.local`, + /** mode file */ `.env.${mode}`, + /** mode local file */ `.env.${mode}.local`, + ] +} + export function loadEnv( mode: string, envDir: string, @@ -18,12 +27,7 @@ export function loadEnv( } prefixes = arraify(prefixes) const env: Record = {} - const envFiles = [ - /** default file */ `.env`, - /** local file */ `.env.local`, - /** mode file */ `.env.${mode}`, - /** mode local file */ `.env.${mode}.local`, - ] + const envFiles = getEnvFilesForMode(mode) const parsed = Object.fromEntries( envFiles.flatMap((file) => { diff --git a/packages/vite/src/node/server/hmr.ts b/packages/vite/src/node/server/hmr.ts index f708b1114ed3cd..245685b3674ef0 100644 --- a/packages/vite/src/node/server/hmr.ts +++ b/packages/vite/src/node/server/hmr.ts @@ -16,6 +16,7 @@ import type { ViteDevServer } from '..' import { isCSSRequest } from '../plugins/css' import { getAffectedGlobModules } from '../plugins/importMetaGlob' import { isExplicitImportRequired } from '../plugins/importAnalysis' +import { getEnvFilesForMode } from '../env' import type { ModuleNode } from './moduleGraph' export const debugHmr = createDebugger('vite:hmr') @@ -62,9 +63,10 @@ export async function handleHMRUpdate( const isConfigDependency = config.configFileDependencies.some( (name) => file === name, ) + const isEnv = config.inlineConfig.envFile !== false && - (fileName === '.env' || fileName.startsWith('.env.')) + getEnvFilesForMode(config.mode).includes(fileName) if (isConfig || isConfigDependency || isEnv) { // auto restart server debugHmr?.(`[config change] ${colors.dim(shortFile)}`)