[英]In Next.js, Is there a way to change the location of the .env file to be outside of the app's folder?
I'm making a project that contains a Next.js app and my.env file is located in the project's root.我正在制作一个包含 Next.js 应用程序的项目,并且 my.env 文件位于项目的根目录中。
How do I make Next.js look for the.env file anywhere except the app's root folder?如何让 Next.js 在应用程序根文件夹以外的任何地方查找 .env 文件?
I already tried using the dotenv package, but unfortunately, that doesn't work.我已经尝试使用 dotenv package,但不幸的是,这不起作用。
In your next.config.js
file configure the dotenv
package as this.在您的
next.config.js
文件中,将dotenv
package 配置为这样。
const path = require('path');
const dotenv = require('dotenv');
dotenv.config({ path: path.join(__dirname, '/path/to/.env') });
To change the location of the.env file, install the 'dotenv' package and add it to your next.config.js file:要更改 .env 文件的位置,请安装“dotenv”package 并将其添加到您的 next.config.js 文件中:
dotenv.config({path: '../.env'})
(In my case the path is ../.env
to go one folder up) (在我的例子中,路径是
../.env
到 go 一个文件夹)
To be able to access the environment variables on the client side declare them in the next.config.js file like that:为了能够在客户端访问环境变量,请在 next.config.js 文件中声明它们,如下所示:
const nextConfig = {
...
//to be able to use the environment variables on the client side
//==============================================================
env: {
EXMAPLE_ENVIRONMENT_VARIABLE: process.env.EXMAPLE_ENVIRONMENT_VARIABLE,
},
...
}
module.exports = nextConfig;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.