diff --git a/docs/config/index.md b/docs/config/index.md index 41b0bfe04a85b7..10863a7b9a88f0 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -322,6 +322,15 @@ export default async ({ command, mode }) => { Set to `false` to prevent Vite from clearing the terminal screen when logging certain messages. Via command line, use `--clearScreen false`. +### envDir + +- **Type:** `string` +- **Default:** `root` + + The directory from which `.env` files are loaded. Can be an absolute path, or a path relative to the project root. + + See [here](/guide/env-and-mode#env-files) for more about environment files. + ## Server Options ### server.host diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index d58063554cb973..4d92ee03b36a6d 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -24,7 +24,7 @@ It will also replace these strings appearing in JavaScript strings and Vue templ ## `.env` Files -Vite uses [dotenv](https://github.com/motdotla/dotenv) to load additional environment variables from the following files in your project root: +Vite uses [dotenv](https://github.com/motdotla/dotenv) to load additional environment variables from the following files in your [environment directory](/config/#envDir): ``` .env # loaded in all cases diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index c5813512f3910b..d8459a39231222 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -155,6 +155,12 @@ export interface UserConfig { * Default: true */ clearScreen?: boolean + /** + * Environment files directory. Can be an absolute path, or a path relative from + * the location of the config file itself. + * @default root + */ + envDir?: string /** * Import aliases * @deprecated use `resolve.alias` instead @@ -304,7 +310,10 @@ export async function resolveConfig( } // load .env files - const userEnv = inlineConfig.envFile !== false && loadEnv(mode, resolvedRoot) + const envDir = config.envDir + ? normalizePath(path.resolve(resolvedRoot, config.envDir)) + : resolvedRoot + const userEnv = inlineConfig.envFile !== false && loadEnv(mode, envDir) // Note it is possible for user to have a custom mode, e.g. `staging` where // production-like behavior is expected. This is indicated by NODE_ENV=production @@ -912,7 +921,7 @@ async function loadConfigFromBundledFile( export function loadEnv( mode: string, - root: string, + envDir: string, prefix = 'VITE_' ): Record { if (mode === 'local') { @@ -939,7 +948,7 @@ export function loadEnv( } for (const file of envFiles) { - const path = lookupFile(root, [file], true) + const path = lookupFile(envDir, [file], true) if (path) { const parsed = dotenv.parse(fs.readFileSync(path), { debug: !!process.env.DEBUG || undefined