Issue
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.
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?
My scripts in 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"
},
My .env vars
TITULO=react, typescript, material ui App
Component
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;
Solution
Next 9.4 has built-in support for .env files: https://nextjs.org/docs/basic-features/environment-variables
But, in case you want to have multiple .env files, like:
- .env.development
- .env.staging
- .env.prestaging
- .env.production
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.
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"
Next would make a production build with ".env.staging" variables.
Answered By - Alexander Kim Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.