如何在 nextjs 中使用不同的 .env 文件? [英] How to use different .env files with nextjs?

查看:164
本文介绍了如何在 nextjs 中使用不同的 .env 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有不同的环境变量配置文件,并能够在我的下一个项目中使用它们.我看到了 dotenv 的示例.

I would like to have different configuration files for the environment variables and be able to use them in my next project. I saw the example with dotenv.

但我不喜欢在 .env 文件中定义变量,也在 config.next.js 文件中定义它们.如果由于某种原因我将变量放在 .env 文件中,但忘记将它们放在 config.next.js 文件中,则代码开始出现问题.有没有更高效的方法?

But I don't like to define the variables in the .env file and also define them in the config.next.js file. if for some reason I put the variables in the .env file but forget to put them in the config.next.js file the code starts having problems. Theres is a way to do it more eficiently?

我在 package.json 中的脚本:

"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "lint": "eslint pages --ext .ts,.tsx,.js",
    "test": "jest",
    "commit": "git-cz",
    "dev:production": "dotenv next"
},

我的 .env 变量

TITULO=react, typescript, material ui App

组件

import { NextPage }          from 'next';
import { FunctionComponent } from 'react';

interface HelloWorldProps {
  nombre: string,
  saludo?: string
}


const HelloWorld: FunctionComponent<HelloWorldProps> = ({ nombre, saludo = 'noches' }: HelloWorldProps) => (
  <>
    <h1>Hola {nombre} buenas {saludo}</h1>
    {/* eslint-disable-next-line multiline-ternary */}
    <h2>{process.env.TITULO ? 'hola' : 'adios'}</h2>
  </>
);

const Home: NextPage = () => <HelloWorld nombre="cristian" />;

export default Home;

推荐答案

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

Next 9.4 has built-in support for .env files: https://nextjs.org/docs/basic-features/environment-variables

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

But, in case you want to have multiple .env files, like:

  • .env.development
  • .env.staging
  • .env.prestaging
  • .env.production

使用内置的环境变量支持是不可能的.目前官方支持的环境只有 3 个,分别是:开发"、测试"、生产".使用 next dev 您可以使用开发"、next build &&next start 使用生产";环境.

It would be impossible to do with a built-in env variables support. There's only 3 environments that officially supported for now, it's: "development", "test", "production". With next dev you use "development", next build && next start uses "production" environment.

如果您需要为生产环境构建,但使用.env.staging";例如,您需要添加 env-cmd 包,并将这一行添加到您的包.json:

If you need to build for production environment, but using ".env.staging" for example, then you need to add env-cmd package, and add this line to your package.json:

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

下一步将使用.env.staging"进行生产构建.变量.

Next would make a production build with ".env.staging" variables.

这篇关于如何在 nextjs 中使用不同的 .env 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆