diff --git a/docs/content/3.docs/1.usage/8.cli.md b/docs/content/3.docs/1.usage/8.cli.md index d9f693b4d5..809a0a29e4 100644 --- a/docs/content/3.docs/1.usage/8.cli.md +++ b/docs/content/3.docs/1.usage/8.cli.md @@ -67,6 +67,10 @@ Option | Default | Description This command sets `process.env.NODE_ENV` to `production`. To override, define `NODE_ENV` in a `.env` file or as command-line argument. +::alert{type=info} +For convenience, in preview mode, your `.env` file will be loaded into `process.env`. (However, in production you will need to ensure your environment variables are set yourself.) +:: + ## Info ```{bash} diff --git a/packages/nuxi/package.json b/packages/nuxi/package.json index f1df1453c9..d94844aabf 100644 --- a/packages/nuxi/package.json +++ b/packages/nuxi/package.json @@ -24,6 +24,7 @@ "@types/mri": "^1.1.1", "@types/rimraf": "^3", "@types/semver": "^7", + "c12": "^0.2.4", "chokidar": "^3.5.3", "clear": "^0.1.0", "clipboardy": "^3.0.0", diff --git a/packages/nuxi/src/commands/preview.ts b/packages/nuxi/src/commands/preview.ts index 8d55d334e4..346d294052 100644 --- a/packages/nuxi/src/commands/preview.ts +++ b/packages/nuxi/src/commands/preview.ts @@ -1,6 +1,7 @@ import { existsSync, promises as fsp } from 'fs' import { dirname, relative } from 'path' import { execa } from 'execa' +import { loadDotenv } from 'c12' import { resolve } from 'pathe' import consola from 'consola' @@ -34,6 +35,11 @@ export default defineNuxtCommand({ process.exit(1) } + if (existsSync(resolve(rootDir, '.env'))) { + consola.info('Loading `.env`. This will not be loaded when running the server in production.') + process.env = await loadDotenv({ cwd: rootDir, fileName: '.env', env: process.env }) + } + consola.info('Starting preview command:', nitroJSON.commands.preview) const [command, ...commandArgs] = nitroJSON.commands.preview.split(' ') consola.log('') diff --git a/yarn.lock b/yarn.lock index c8b97c3ed8..b81e3712b3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -15369,6 +15369,7 @@ __metadata: "@types/mri": ^1.1.1 "@types/rimraf": ^3 "@types/semver": ^7 + c12: ^0.2.4 chokidar: ^3.5.3 clear: ^0.1.0 clipboardy: ^3.0.0