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

查看:151
本文介绍了如何在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

使用内置的env变量支持是不可能的.目前只有3种正式支持的环境:开发",测试",生产".通过 next dev ,您可以使用"development", next build&&下次启动使用生产"环境.

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 包,并将此行添加到您的package.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天全站免登陆