dotenv 文件未加载环境变量
我在 root 文件夹 文件中有 .env 文件
NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user
,在 root/app/config/server.js
文件夹中有 server.js
文件。 server.js
文件的第一行是
require('dotenv').config();
我还尝试了以下操作:
require('dotenv').config ({路径: '../.env'})
;
require('dotenv').config({path: '../../.env'})
;
但是,当我运行 server.js
文件时,我的环境变量没有加载 从命令提示符
node root/app/config/server.js
如果我使用Visual Studio并按F5 ,它加载了!
我不确定我做错了什么,我错过了什么。 任何建议都将受到高度赞赏。谢谢。
I have .env file at root folder file
NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user
And server.js
file in the root/app/config/server.js
folder.
The first line of server.js
file is
require('dotenv').config();
I also tried following:
require('dotenv').config({path: '../.env'})
;
require('dotenv').config({path: '../../.env'})
;
However, my env variable are not loaded when I run the server.js
file
from command prompt
node root/app/config/server.js
If I use the visual studio and press F5, it loads!!
I'm not sure what I'm doing wrong, what I'm missing.
Any suggestion is highly appreciate. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
使用
require('dotenv').config({path:__dirname+'/./../../.env'})
怎么样?你的问题似乎是执行路径。
How about use
require('dotenv').config({path:__dirname+'/./../../.env'})
?Your problem seems to be the execution path.
这解决了我在 Node
v8.14.1
中的问题:简单地执行
会导致一个位置解析为
This solved my issues in Node
v8.14.1
:Simply doing
resulted in a location that resolved as
这是一个单行解决方案:
这将递归父目录,直到找到要使用的 .env 文件。
您还可以使用这个名为 ckey 的模块,其灵感来自于一行多于。
主目录中的 .env 文件。
子目录中的一些js文件
Here is a single-line solution:
This will recurse parent directories until it finds a .env file to use.
You can also alternatively use this module called ckey inspired from one-liner above.
.env file from main directory.
some js file from sub-directory
如果您从嵌套文件调用
dotenv
,并且您的.env
文件位于项目根目录,则您想要连接这些点的方式是通过以下方式:If you are invoking
dotenv
from a nested file, and your.env
file is at the project root, the way you want to connect the dots is via the following:@DavidP 的答案中的评论之一记录了 dotenv.config 的输出,
这将输出配置日志并显示错误。就我而言,它表明配置方法正在引用当前目录而不是
包含我的 .env 文件的父目录。我可以通过以下内容进行参考
One of the comments in @DavidP's answer notes logging the output of dotenv.config with
This will output a log of the config and display errors. In my case it indicated the config method was referencing the current directory instead of the
parent directory which contained my .env file. I was able to reference that with the following
我遇到了这个问题,结果发现 REACT 只加载以 REACT_APP_ 为前缀的变量
VueJs 可能有类似的问题,因为它期望变量以以下前缀: VUE_APP_
I've had this problem and it turned out that REACT only loads variables prefixed with REACT_APP_
VueJs can have a similar issue as it expects variables to be prefixed with: VUE_APP_
确保在入口文件的开头加载
.env
(例如index.js
或server.js
)。有时,执行顺序会在服务启动后加载环境变量。并且,通过使用__dirname
,它可以轻松地指向相对于当前文件所需的文件。这里我的项目结构是这样的。
Be sure to load
.env
at the beginning of the entry file (e.g.index.js
orserver.js
). Sometimes, the order of execution loads the environment variables after the services are initiated. And, by using__dirname
, it can easily point to the file required relative to the current file.Here my project structure is like this.
在您到达到目前为止的远程情况下,我的问题相当愚蠢:
我错误地用冒号“:”而不是等于“=”命名了我的环境变量。菜鸟错误,但结果是没有加载拼写错误的变量赋值。
In the remote case that you arrive till this point, my issue was quite dumber:
I wrongly named my env variables with colon ":" instead of equals "=". Rookie mistake but the resulting behavior was not loading the misspelled variables assignment.
您可以首先使用以下方法进行调试:
在我的场景中,我的
.env
文件位于根目录中,我需要在嵌套目录中使用它。结果给了我:所以我简单地解析结果并将其存储在一个变量中:
然后像 JS 对象一样访问我的 DATABASE_URL:
You can first debug by using:
In my scenario, my
.env
file is in root directory and I need to use it in a nested directory. The result gives me:So I simply parse the result and store it in a variable:
Then access my DATABASE_URL like a JS object:
这为我解决了这个问题:
This solved the issue for me:
试试这个:
对我有用,不知道怎么样?
Try this:
worked for me idk how??
这让我有些头疼,将 require 语句的输出记录到控制台的提示非常有用。
console.log(require('dotenv').config());
结果我是用
nodemon application_name/.
从我的 user/ 目录运行我的应用程序,那就是让 dotenv 在我的主目录而不是应用程序的目录中查找 .env 文件。我很懒,跳过了一张cd
,这花了我几分钟的时间。It took me a few head scratches, and the tip to log the output of the require statement to console was really helpful.
console.log(require('dotenv').config());
Turns out I was running my app from my user/ directory with
nodemon application_name/.
and that was making dotenv look for the .env file in my home dir instead of the app's. I was lazy by skipping onecd
and that cost me a few minutes.我发现在配置中发送了一个选项
debug: true
,它向我显示了以下内容:
我添加了
overwrite: true
并使其正常工作:我知道我可能为时已晚回答,但在检查文档几个小时后决定分享我的发现。
I found an option
debug: true
to be sent in the configwhich showed me the following:
I added
overwrite: true
and got it working:I know I might be too late answering, but decided to share my findings after hours of checking the documentation.
我在 Windows 中遇到
.env
文件的编码问题。它采用 UTF-16LE 编码。该文件已被解析,但被认为是空的。在我将.env
文件转换为 UTF-8 后,一切都按预期工作。I had a problem with the file encoding of the
.env
file in windows. It was encoded in UTF-16LE. The file was parsed but it was considered empty. After i converted the.env
file to UTF-8 everything works as expected.就我而言,
.env
读起来很好,但.env.local
则不然。更新
package.json
将.env
命名为.env.local
(cp ./.env.local .env)解决了问题:
In my case
.env
was read fine, but not.env.local
.Updating
package.json
to name.env
into.env.local
(cp ./.env.local .env
) solved the problem:如果 config.env 文件和 index.js 文件都存在于同一目录中:
然后,文件:index.js
文件:config.env:
if config.env file and index.js file both present in the same directory:
then, file: index.js
file: config.env:
如果您安装了
dotenv
作为生产依赖项。那么,它可能无法正常工作。.env
文件通常在开发期间使用dotenv
将环境变量导入应用程序环境时使用。所以,并非如此:
要使
dotenv
库正常工作,您始终需要提及该代码:在文件的 Top 中,如下所示:
如果你把这个配置放在中间。然后,您将看到一些有线行为。就像,在某些文件
env
变量工作文件中。但在某些情况下,情况并非如此。If you are installed
dotenv
as production dependency. Then, it may not work properly. The.env
file is commonly utilized during development when usingdotenv
to import environment variables into the application's environment. So,Not that:
To working properly of
dotenv
library, you always need to mention that code:In Top of the file like this:
If you put that configuration in the middle. Then, you will see some wired behavior. Like, in some file
env
variable working file. But, in some, it is not.从 Node 版本 20.6.0 开始,您不再需要使用 dotenv 包,因为该功能现已内置。
假设您的目录中有一个
.env
文件,如下所示:您可以使用
--env- 轻松将
标志:.env
文件中的变量设置为环境变量file设置后,这些环境变量可以作为 process.env 的属性进行访问:
运行该命令将产生以下输出:
Starting from Node version 20.6.0, you no longer need to use the dotenv package as the functionality is now built-in.
Assuming you have a
.env
file in your directory like this:You can easily set the variables in the
.env
file as environment variables using the--env-file
flag:Once set, these environment variables can be accessed as properties of
process.env
:Running the command will produce the following output:
您可能需要 .env 文件相对于启动应用程序的当前工作目录的路径。
您可以像这样创建此路径:
process.cwd()
返回工作目录的绝对路径。__dirname
返回应用程序的绝对路径。path.join()
将 .env 文件的路径添加到应用程序的路径中。因此,如果您的 .env 文件嵌套得更深,只需添加文件夹(例如path.join(__dirname, 'config', 'secret','.env')
)path.relative()
创建相对路径。You can need the path of the .env file relative to the current working directory from where the application was launched.
You can create this path like this:
process.cwd()
returns the absolute path of the working directory.__dirname
returns the absolute path of the application.path.join()
adds the path of the .env-file to the path of the application. so if your .env file is nested deeper, just add the folders (e.g.path.join(__dirname, 'config', 'secret','.env')
)path.relative()
creates the relative path.打字稿。
如果您尝试解析 __dirname 并在另一个文件夹中编译源文件夹,请确保编辑 __dirname。就我而言,我在 dist 文件夹中编译 ts,并且 env 文件不位于 dist 文件夹中,而是位于根文件夹中。所以你应该从 __dirname 中删除 /dist。要调试它,您可以调用 error() 函数,如果读取 env 文件出现问题,该函数将返回错误。
另一件事,当您设置环境变量时,请确保以下内容:
变量和 (&&) 之间没有空格,如下所示
Typescript.
if you are trying to resolve __dirname and you are compiling your source folder in another folder, make sure that you edit __dirname. in my case i am compiling ts in dist folder and env files are not located in dist folder, but in the root folder. so you should delete /dist from __dirname. To debug it, you can call error() function which returns error if there is problem with reading env file.
another thing, when you set env variables make sure that following:
no space between variable and (&&) as following
直到我最终添加
override: true
这是我的完整代码
Nothing worked for me until I finally added
override: true
Here is my full code
有一次我也遇到了同样的问题。 Dotenv 未加载 .env 文件。我尝试使用路径配置来解决此问题,将 .env 文件放在根文件夹中,将 .env 放在文件运行的文件夹中,但没有任何帮助。然后我只是删除了 Node_modules 文件夹,重新安装所有依赖项,它就可以正常工作了
One time I have got the same problem. Dotenv did not load .env file. I tried to fix this problem with a path config, to put .env file in a root folder, to put .env in the folder where the file is running and nothing helps me. Then I just trashed Node_modules folder, reinstall all dependencies and it works correctly
我正在使用:
I'am using:
使用 Playwright / typescript 对我有用的方法:
1 创建文件并将其放置在项目的根目录中:
global-setup.ts
里面添加:
2 然后将此文件使用到
playwright.config.ts
中,如下:
globalSetup: require.resolve('./global-setup'),
这样,全局conf 已创建,并在每个测试中进行拾取。
What worked for me using Playwright / typescript:
1 create file and place at the root of the project:
global-setup.ts
add inside:
2 Then use this file into
playwright.config.ts
as:
globalSetup: require.resolve('./global-setup'),
In this way, global conf is created, and pickup in every single test.
对于 ES6,你需要这样做:
For ES6 you need to do this way:
如果您使用其他工具(全局安装)在某处调用您的配置文件,则仅使用绝对路径...
Use only absolute path if you are using some other tool(installed globally) to call your config file somewhere ...
如何防止 vite.js 在源代码中暴露 env 变量
这是 proccess.env 访问 .env 变量的配置
斜体文本
只有以 VITE_ 为前缀的变量才会暴露给您的 Vite 处理代码。
例如,对于以下环境变量:
只有 VITE_SOME_KEY 将公开为 import.meta.env.VITE_SOME_KEY
https://vitejs.dev/config/shared-options.html#envprefix
**请注意,如果您使用以下代码,它会公开源代码中的所有变量:
how prevent exposing env variables in the source code by vite.js
this is a config for acces .env variable by proccess.env
Italic Text
only variables prefixed with VITE_ are exposed to your Vite-processed code.
e.g. for the following env variables:
Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY
https://vitejs.dev/config/shared-options.html#envprefix
**note that if you use the following code it expose all variable in youre source code:
在 .env 文件中使用“=”定义键值,不要使用冒号“:”
例如下面是不正确的
USER:root
这是在 .env 文件中定义 env 变量的正确方法
USER =根
In .env file use "=" to define key value do not use colon ":"
For example below is incorrect
USER:root
This is correct way to define env variables in .env file
USER=root
我的失败是路径关键字。应该是 P 而不是大写字母。太有趣了
My failer was the path keyword . should be the P not capital Letter . that was so funny