乐闻世界logo
搜索文章和话题

How to use different env files with nextjs?

6 个月前提问
2 个月前修改
浏览次数546

6个答案

1
2
3
4
5
6

在Next.js中,管理不同环境(开发、测试、生产)的配置可以通过使用不同的.env文件实现。Next.js支持环境变量的加载,并且有一套特定的规则用于加载不同环境的.env文件。以下是如何使用不同的.env文件的步骤:

  1. 创建.env文件: 在Next.js项目的根目录中,你可以创建以下.env文件来定义环境变量:

    • .env.local: 可以覆盖其他.env文件中的变量,不会被git版本控制系统跟踪,通常用于包含敏感信息。
    • .env.development: 只在next dev(即开发环境)中被加载。
    • .env.production: 只在next start(即生产环境)中被加载。
    • .env.test: 在执行自动化测试时使用,需要自己配置加载机制。
    • .env: 默认的环境变量文件,无论何种环境都会被加载,但会被以上特定环境的配置覆盖。
  2. 设置环境变量: 在每个.env文件中,设置必要的环境变量,格式如下:

    plaintext
    # .env.local API_SECRET=local_secret # .env.development API_URL=https://dev.example.com/api # .env.production API_URL=https://prod.example.com/api
  3. 加载环境变量: Next.js会自动加载这些变量,无需额外的配置。你可以在代码中通过process.env来访问这些变量:

    javascript
    console.log(process.env.API_URL); // 输出将根据当前环境加载对应的.env文件中的变量值
  4. 使用环境变量: 你可以在Next.js的页面、API路由、getServerSidePropsgetStaticProps等服务器端代码中直接使用process.env来访问环境变量。

  5. 公开环境变量到浏览器: 如果需要在浏览器中使用环境变量,你需要在环境变量名前加上NEXT_PUBLIC_前缀:

    plaintext
    NEXT_PUBLIC_ANALYTICS_ID=xyz123

    这样,你可以在客户端JavaScript中安全地使用这些变量:

    javascript
    console.log(process.env.NEXT_PUBLIC_ANALYTICS_ID); // 客户端也可访问

示例:

假设你有一个API的URL,在开发环境和生产环境中是不同的。你可以如下设置环境变量:

  • .env.development文件中:

    plaintext
    API_URL=https://dev.api.example.com
  • .env.production文件中:

    plaintext
    API_URL=https://api.example.com

当你在开发环境下运行next dev时,process.env.API_URL将会是https://dev.api.example.com。而当你在生产环境下运行next start时,环境变量将会是https://api.example.com

通过这种方式,你可以根据当前的运行环境加载不同的环境变量,而不需要在代码中做任何改变,这有助于项目配置的管理和代码的可维护性。

2024年6月29日 12:07 回复

Next 9.4 内置了对 .env 文件的支持:https://nextjs.org/docs/basic-features/environment-variables

但是,如果您想要有多个 .env 文件,例如:

  • .env.development
  • .env.staging
  • .env.预演
  • .env.生产

使用内置环境变量支持是不可能的。目前官方只支持3种环境,分别是:“开发”、“测试”、“生产”。与next dev您使用“开发”环境,next build && next start使用“生产”环境。

如果您需要构建生产环境,但使用“.env.staging”为例,那么您需要添加env-cmd包,并将此行添加到 package.json 中:

shell
"build:staging": "env-cmd -f .env.staging yarn build && yarn start"

接下来将使用“.env.staging”变量进行生产构建。

2024年6月29日 12:07 回复

大多数这些答案的问题是它们违背了“构建一次,到处运行”的原则,实际上我们大多数人都使用这种技术构建并通过 Docker 容器运行。不可能有多个像这样的构建命令,这将是不好的做法。

最好让您的环境在运行时可用。我们创建了一个允许下一步静态优化的包,并且仍然具有运行时环境变量window.__ENV

https://github.com/andrewmclagan/react-env

这是通过在运行时从白名单环境变量生成环境配置对象来实现的:

shell
{ ... "scripts": { "dev": "react-env -- next dev", // where .env.${APP_ENV} "start": "react-env --env APP_ENV -- next start" // where .env.${APP_ENV} } ... }
2024年6月29日 12:07 回复

可以通过以下两种方式在 nextjs 中拥有不同的 .env 文件:

1.使用env-cmd包

在脚本中提供环境文件的路径,例如:

shell
"scripts": { "start": "env-cmd path/to/prod/env/file next start", "start:dev": "env-cmd path/to/prod/env/file next dev", "build:dev": "env-cmd path/to/dev/env/file next build", "build:test": "env-cmd path/to/test/env/file next build", "build:stage": "env-cmd path/to/stage/env/file next build", "build": "env-cmd path/to/stage/prod/file next build", },

2.使用dotenv包

在 next.config.js 文件中添加以下内容:

shell
require("dotenv").config({ path: `${process.env.ENVIRONMENT}` }); module.exports = { // your configs }

并在您的脚本中提供环境变量,例如:

shell
"scripts": { "start": "ENVIRONMENT=path/to/prod/env/file next start", "start:dev": "ENVIRONMENT=path/to/dev/env/file next dev", "build:dev": "ENVIRONMENT=path/to/dev/env/file next build", "build:test": "ENVIRONMENT=path/to/test/env/file next build", "build:stage": "ENVIRONMENT=path/to/stage/env/file next build", "build": "ENVIRONMENT=path/to/stage/prod/file next build", },

注意:不要将您的 .env* 文件放在根文件夹中,否则 NEXT 将从您的 .evn* 文件中自动选择,并且它仅支持生产和开发阶段。所以它会忽略其他 .env.my-stage 文件。

2024年6月29日 12:07 回复

如今,您不需要安装任何额外的东西来实现多环境配置!请参阅具有配置管理功能的 GitHub 存储库NextJS 模板

Next.js v9.4 及更高版本有一种更直观、更符合人体工程学的方式来添加环境变量

shell
{ "name": "package.json", "scripts": { "dev": "next dev", "build": "next build && next export", "build-dev": "TARGET_ENV=development next build && next export", "build-staging": "TARGET_ENV=staging next build && next export", "test": "jest --watch" } } { "name": "env.json", "development": { "APP_ENV": "development" }, "production": { "APP_ENV": "production" }, "staging": { "APP_ENV": "staging" }, "test": { "APP_ENV": "test" } } // next.config.js v9.4+ const envConfig = require('./env.json') const environment = process.env.TARGET_ENV || process.env.NODE_ENV const nextConfig = { env: envConfig[environment], // getEnvConfig() } module.exports = nextConfig function getEnvConfig() { // for multi-file config try { return require(`./env-${environment}.json`) } catch (err) { return require('./env.json') } } npm run dev # process.env.APP_ENV=development npm run build # process.env.APP_ENV=production npm run build-dev # process.env.APP_ENV=development npm run build-staging # process.env.APP_ENV=staging npm run test # process.env.APP_ENV=test
2024年6月29日 12:07 回复

对于任何有兴趣使用.yml文件来轻松管理环境变量的人,我是这样做的。

**yenv**在 中安装一个插件devDependencies

在next.config.js中添加以下配置:

shell
const path = require("path"); const yenv = require("yenv"); const { PHASE_DEVELOPMENT_SERVER } = require("next/constants"); module.exports = (phase) => { const isDev = phase === PHASE_DEVELOPMENT_SERVER; const NEXT_ENV = isDev ? "development" : process.env.APP_ENV; const rawEnv = yenv(path.resolve(".env.yml"), { raw: true, env: NEXT_ENV }); return { ...some other config, env: getEnvVars(rawEnv, isDev).raw, compress: true, }; }; function getEnvVars(rawEnv, dev) { const NEXT_PUBLIC = /^NEXT_PUBLIC_/i; const raw = Object.keys(rawEnv) .filter((key) => NEXT_PUBLIC.test(key)) .reduce((env, key) => { env[key] = rawEnv[key]; return env; }, {}); // Stringify all values so we can feed into Webpack DefinePlugin const stringified = { "process.env": Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}), }; return { raw, stringified }; }

现在只需根据**package.json**脚本中的环境添加不同的构建命令即可。

shell
"scripts": { "dev": "node server.js", "build:production": "APP_ENV=production next build", "build:staging": "APP_ENV=staging next build", "start": "NODE_ENV=production node server.js" },

现在您可以通过单个文件使用环境变量,**.env.yml**如下所示:

shell
base: NEXT_PUBLIC_SECRET_KEY : "" NEXT_PUBLIC_ANOTHER_SECRET: "" development: ~compose: base NEXT_PUBLIC_SECRET_KEY: "bnbnfjf" staging: ~compose: base NEXT_PUBLIC_SECRET_KEY: "absadsad" production: ~compose: base NEXT_PUBLIC_SECRET_KEY: "lasjdasodsdsad"

现在您可以调用npm run build:production加载生产环境变量和npm run build:staging暂存环境变量。

这提供了为您的用例提供任意数量的环境的好处。您只需要添加一个构建命令,并更新环境变量.env.yml就可以了。

2024年6月29日 12:07 回复

你的答案