Skip to main content

dotenv 中文网

Dotenv 是一个零依赖模块,可将环境变量从 .env 文件加载到 process.env 中。将配置存储在与代码分开的环境中基于 十二要素应用 方法。

¥Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

🌱 安装

¥🌱 Install

# install locally (recommended)
npm install dotenv --save

或者用 yarn 安装?yarn add dotenv

¥Or installing with yarn? yarn add dotenv

🏗️ 用法

¥🏗️ Usage

在项目的根目录中创建一个 .env 文件(如果使用像 apps/backend/app.js 这样的 monorepo 结构,请将其放在你的 app.js 进程运行的文件夹的根目录中):

¥Create a .env file in the root of your project (if using a monorepo structure like apps/backend/app.js, put it in the root of the folder where your app.js process runs):

S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"

在你的应用中尽早导入和配置 dotenv:

¥As early as possible in your application, import and configure dotenv:

require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it is working

.. 或使用 ES6?

¥.. or using ES6?

import 'dotenv/config'

就是这样。process.env 现在具有你在 .env 文件中定义的键和值:

¥That's it. process.env now has the keys and values you defined in your .env file:

require('dotenv').config()

...

s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})

多行值

¥Multiline values

如果你需要多行变量,例如私钥,现在支持(>= v15.0.0)换行符:

¥If you need multiline variables, for example private keys, those are now supported (>= v15.0.0) with line breaks:

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"

或者,你可以双引号字符串并使用 \n 字符:

¥Alternatively, you can double quote strings and use the \n character:

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"

评论

¥Comments

注释可以添加到你的文件中的单独一行或内联中:

¥Comments may be added to your file on their own line or inline:

# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"

注释从 # 存在的地方开始,因此如果你的值包含 #,请将其括在引号中。这是从 >= v15.0.0 开始的重大变化。

¥Comments begin where a # exists, so if your value contains a # please wrap it in quotes. This is a breaking change from >= v15.0.0 and on.

解析

¥Parsing

解析包含环境变量的文件内容的引擎可供使用。它接受字符串或缓冲区,并将返回带有解析后的键和值的对象。

¥The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.

const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }

预加载

¥Preload

注意:考虑使用 dotenvx 而不是预加载。我现在正在这样做(并推荐这样做)。

¥Note: Consider using dotenvx instead of preloading. I am now doing (and recommending) so.

它具有相同的用途(你不需要要求和加载 dotenv),增加了更好的调试功能,并且可以与任何语言、框架或平台配合使用。– motdotla

¥It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. – motdotla

你可以使用 --require (-r) 命令行选项 预加载 dotenv。通过这样做,你无需在应用代码中要求和加载 dotenv。

¥You can use the --require (-r) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.

$ node -r dotenv/config your_script.js

以下配置选项以 dotenv_config_<option>=value 格式的命令行参数形式受支持

¥The configuration options below are supported as command line arguments in the format dotenv_config_<option>=value

$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true

此外,你可以使用环境变量来设置配置选项。命令行参数将位于这些参数之前。

¥Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.

$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env

变量扩展

¥Variable Expansion

你需要在其中一个变量中添加另一个变量的值吗?使用 dotenv-expand

¥You need to add the value of another variable in one of your variables? Use dotenv-expand.

命令替换

¥Command Substitution

使用 dotenvx 使用命令替换。

¥Use dotenvx to use command substitution.

将命令的输出添加到 .env 文件中的一个变量中。

¥Add the output of a command to one of your variables in your .env file.

# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (1) from .env
DATABASE_URL postgres://yourusername@localhost/my_database

同步

¥Syncing

你需要在机器、环境或团队成员之间保持 .env 文件同步吗?使用 dotenvx 加密你的 .env 文件并安全地将它们包含在源代码控制中。这仍然遵循十二因素应用规则,通过生成与代码分开的解密密钥。

¥You need to keep .env files in sync between machines, environments, or team members? Use dotenvx to encrypt your .env files and safely include them in source control. This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.

多个环境

¥Multiple Environments

使用 dotenvx 生成 .env.ci.env.production 文件等。

¥Use dotenvx to generate .env.ci, .env.production files, and more.

部署

¥Deploying

你需要以与云无关的方式部署你的密钥吗?使用 dotenvx 生成在你的生产服务器上设置的私有解密密钥。

¥You need to deploy your secrets in a cloud-agnostic manner? Use dotenvx to generate a private decryption key that is set on your production server.

🌴 管理多个环境

¥🌴 Manage Multiple Environments

使用 dotenvx

¥Use dotenvx

在本地运行任何环境。创建一个 .env.ENVIRONMENT 文件并使用 --env-file 加载它。它很简单,但很灵活。

¥Run any environment locally. Create a .env.ENVIRONMENT file and use --env-file to load it. It's straightforward, yet flexible.

$ echo "HELLO=production" > .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js

$ dotenvx run --env-file=.env.production -- node index.js
Hello production
> ^^

或有多个 .env 文件

¥or with multiple .env files

$ echo "HELLO=local" > .env.local
$ echo "HELLO=World" > .env
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js

$ dotenvx run --env-file=.env.local --env-file=.env -- node index.js
Hello local

更多环境示例

¥more environment examples

🚀 部署

¥🚀 Deploying

使用 dotenvx

¥Use dotenvx.

使用单个命令为你的 .env 文件添加加密。传递 --encrypt 标志。

¥Add encryption to your .env files with a single command. Pass the --encrypt flag.

$ dotenvx set HELLO Production --encrypt -f .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js

$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
[dotenvx] injecting env (2) from .env.production
Hello Production

了解更多

¥learn more

📚 示例

¥📚 Examples

有关将 dotenv 与各种框架、语言和配置一起使用的信息,请参阅 examples

¥See examples of using dotenv with various frameworks, languages, and configurations.

📖 文档

¥📖 Documentation

Dotenv 公开了四个功能:

¥Dotenv exposes four functions:

  • config

  • parse

  • populate

  • decrypt

配置

¥Config

config 将读取你的 .env 文件,解析内容,将其分配给 process.env,并返回一个包含已加载内容的 parsed 键的对象,如果失败则返回 error 键。

¥config will read your .env file, parse the contents, assign it to process.env, and return an Object with a parsed key containing the loaded content or an error key if it failed.

const result = dotenv.config()

if (result.error) {
throw result.error
}

console.log(result.parsed)

你还可以将选项传递给 config

¥You can additionally, pass options to config.

选项

¥Options

path

默认:path.resolve(process.cwd(), '.env')

¥Default: path.resolve(process.cwd(), '.env')

如果包含环境变量的文件位于其他地方,请指定自定义路径。

¥Specify a custom path if your file containing environment variables is located elsewhere.

require('dotenv').config({ path: '/custom/path/to/.env' })

默认情况下,config 将在当前工作目录中查找名为 .env 的文件。

¥By default, config will look for a file called .env in the current working directory.

将多个文件作为数组传入,它们将按顺序进行解析并与 process.env(或 option.processEnv,如果已设置)组合。变量的第一个值将获胜,除非设置了 options.override 标志,在这种情况下最后一个值将获胜。如果 process.env 中已经存在某个值,并且未设置 options.override 标志,则不会对该值进行任何更改。

¥Pass in multiple files as an array, and they will be parsed in order and combined with process.env (or option.processEnv, if set). The first value set for a variable will win, unless the options.override flag is set, in which case the last value set will win. If a value already exists in process.env and the options.override flag is NOT set, no changes will be made to that value.

require('dotenv').config({ path: ['.env.local', '.env'] })
encoding

默认:utf8

¥Default: utf8

指定包含环境变量的文件的编码。

¥Specify the encoding of your file containing environment variables.

require('dotenv').config({ encoding: 'latin1' })
debug

默认:false

¥Default: false

打开日志记录以帮助调试为什么某些键或值未按预期设置。

¥Turn on logging to help debug why certain keys or values are not being set as you expect.

require('dotenv').config({ debug: process.env.DEBUG })
override

默认:false

¥Default: false

使用 .env 文件中的值覆盖已在你的机器上设置的任何环境变量。如果 option.path 中提供了多个文件,则在每个文件与下一个文件组合时也将使用覆盖。如果不设置 override,则第一个值获胜。设置 override 后,最后一个值获胜。

¥Override any environment variables that have already been set on your machine with values from your .env file(s). If multiple files have been provided in option.path the override will also be used as each file is combined with the next. Without override being set, the first value wins. With override set the last value wins.

require('dotenv').config({ override: true })
processEnv

默认:process.env

¥Default: process.env

指定要将密钥写入的对象。默认为 process.env 环境变量。

¥Specify an object to write your secrets to. Defaults to process.env environment variables.

const myObject = {}
require('dotenv').config({ processEnv: myObject })

console.log(myObject) // values from .env
console.log(process.env) // this was not changed or written to

解析

¥Parse

解析包含环境变量的文件内容的引擎可供使用。它接受字符串或缓冲区,并将返回带有解析后的键和值的对象。

¥The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.

const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }

选项

¥Options

debug

默认:false

¥Default: false

打开日志记录以帮助调试为什么某些键或值未按预期设置。

¥Turn on logging to help debug why certain keys or values are not being set as you expect.

const dotenv = require('dotenv')
const buf = Buffer.from('hello world')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// expect a debug message because the buffer is not in KEY=VAL form

填充

¥Populate

将 .env 文件的内容填充到 process.env 的引擎可供使用。它接受目标、源和选项。这对于想要提供自己的对象的高级用户很有用。

¥The engine which populates the contents of your .env file to process.env is available for use. It accepts a target, a source, and options. This is useful for power users who want to supply their own objects.

例如,自定义源:

¥For example, customizing the source:

const dotenv = require('dotenv')
const parsed = { HELLO: 'world' }

dotenv.populate(process.env, parsed)

console.log(process.env.HELLO) // world

例如,自定义源和目标:

¥For example, customizing the source AND target:

const dotenv = require('dotenv')
const parsed = { HELLO: 'universe' }
const target = { HELLO: 'world' } // empty object

dotenv.populate(target, parsed, { override: true, debug: true })

console.log(target) // { HELLO: 'universe' }

options

调试

¥Debug

默认:false

¥Default: false

打开日志记录以帮助调试为什么某些键或值未按预期填充。

¥Turn on logging to help debug why certain keys or values are not being populated as you expect.

override

默认:false

¥Default: false

覆盖已设置的任何环境变量。

¥Override any environment variables that have already been set.

❓ 常见问题

¥❓ FAQ

为什么 .env 文件无法成功加载我的环境变量?

¥Why is the .env file not loading my environment variables successfully?

很可能你的 .env 文件不在正确的位置。查看此堆栈溢出

¥Most likely your .env file is not in the correct place. See this stack overflow.

打开调试模式并重试。

¥Turn on debug mode and try again..

require('dotenv').config({ debug: true })

你将收到一个有用的错误输出到你的控制台。

¥You will receive a helpful error outputted to your console.

我应该提交我的 .env 文件吗?

¥Should I commit my .env file?

不。我们强烈建议不要将你的 .env 文件提交到版本控制。它应该只包含特定于环境的值,例如数据库密码或 API 密钥。你的生产数据库应该具有与开发数据库不同的密码。

¥No. We strongly recommend against committing your .env file to version control. It should only include environment-specific values such as database passwords or API keys. Your production database should have a different password than your development database.

我应该有多个 .env 文件吗?

¥Should I have multiple .env files?

我们建议每个环境创建一个 .env 文件。使用 .env 进行本地/开发,.env.production 进行生产等等。这仍然遵循十二因素原则,因为每个原则都单独归因于其自己的环境。避免以某种方式在继承中起作用的自定义设置(例如,.env.production 继承了 .env 的值)。最好在每个 .env.environment 文件中重复值(如果需要)。

¥We recommend creating one .env file per environment. Use .env for local/development, .env.production for production and so on. This still follows the twelve factor principles as each is attributed individually to its own environment. Avoid custom set ups that work in inheritance somehow (.env.production inherits values form .env for example). It is better to duplicate values if necessary across each .env.environment file.

在十二要素应用中,环境变量是细粒度的控件,每个变量都与其他环境变量完全正交。它们永远不会被组合在一起作为“环境”,而是针对每个部署进行独立管理。这是一个随着应用在其生命周期内自然扩展到更多部署而顺利扩展的模型。

¥In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.

十二要素应用

¥– The Twelve-Factor App

解析引擎遵循哪些规则?

¥What rules does the parsing engine follow?

解析引擎当前支持以下规则:

¥The parsing engine currently supports the following rules:

  • BASIC=basic 变成 {BASIC: 'basic'}

    ¥BASIC=basic becomes {BASIC: 'basic'}

  • 跳过空行

    ¥empty lines are skipped

  • # 开头的行被视为注释

    ¥lines beginning with # are treated as comments

  • # 标记注释的开始(除非值用引号括起来)

    ¥# marks the beginning of a comment (unless when the value is wrapped in quotes)

  • 空值变为空字符串(EMPTY= 变为 {EMPTY: ''}

    ¥empty values become empty strings (EMPTY= becomes {EMPTY: ''})

  • 保留内部引号(想想 JSON)(JSON={"foo": "bar"} 变为 {JSON:"{\"foo\": \"bar\"}"

    ¥inner quotes are maintained (think JSON) (JSON={"foo": "bar"} becomes {JSON:"{\"foo\": \"bar\"}")

  • 未加引号的值两端的空格被删除(有关 trim 的更多信息)(FOO= some value 变为 {FOO: 'some value'}

    ¥whitespace is removed from both ends of unquoted values (see more on trim) (FOO= some value becomes {FOO: 'some value'})

  • 单引号和双引号值被转义(SINGLE_QUOTE='quoted' 变为 {SINGLE_QUOTE: "quoted"}

    ¥single and double quoted values are escaped (SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: "quoted"})

  • 单引号和双引号值保留两端的空格(FOO=" some value " 变为 {FOO: ' some value '}

    ¥single and double quoted values maintain whitespace from both ends (FOO=" some value " becomes {FOO: ' some value '})

  • 双引号值扩展新行(MULTILINE="new\nline" 变为

    ¥double quoted values expand new lines (MULTILINE="new\nline" becomes

{MULTILINE: 'new
line'}
  • 支持反引号 (BACKTICK_KEY=This has 'single' and "double" quotes inside of it.``)

    ¥backticks are supported (BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.`)

已经设置的环境变量会发生什么?

¥What happens to environment variables that were already set?

默认情况下,我们永远不会修改任何已设置的环境变量。特别是,如果你的 .env 文件中有一个变量与你环境中已经存在的变量相冲突,那么该变量将被跳过。

¥By default, we will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped.

如果你想覆盖 process.env,请使用 override 选项。

¥If instead, you want to override process.env use the override option.

require('dotenv').config({ override: true })

为什么我的环境变量没有显示在 React 中?

¥How come my environment variables are not showing up for React?

你的 React 代码在 Webpack 中运行,其中 fs 模块甚至 process 全局变量本身都无法开箱即用。process.env 只能通过 Webpack 配置注入。

¥Your React code is run in Webpack, where the fs module or even the process global itself are not accessible out-of-the-box. process.env can only be injected through Webpack configuration.

如果你使用的是通过 create-react-app 分发的 react-scripts,它内置了 dotenv,但有一个怪癖。在你的环境变量前面加上 REACT_APP_。有关更多详细信息,请参阅 此堆栈溢出

¥If you are using react-scripts, which is distributed through create-react-app, it has dotenv built in but with a quirk. Preface your environment variables with REACT_APP_. See this stack overflow for more details.

如果你使用的是其他框架(例如 Next.js、Gatsby……),则需要查阅它们的文档以了解如何将环境变量注入客户端。

¥If you are using other frameworks (e.g. Next.js, Gatsby...), you need to consult their documentation for how to inject environment variables into the client.

我可以为 dotenv 定制/编写插件吗?

¥Can I customize/write plugins for dotenv?

是的!dotenv.config() 返回一个表示已解析 .env 文件的对象。这为你提供了继续在 process.env 上设置值所需的一切。例如:

¥Yes! dotenv.config() returns an object representing the parsed .env file. This gives you everything you need to continue setting values on process.env. For example:

const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)

如何将 dotenv 与 import 一起使用?

¥How do I use dotenv with import?

简单..

¥Simply..

// index.mjs (ESM)
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'

一点背景知识..

¥A little background..

当你运行包含 import 声明的模块时,它导入的模块首先被加载,然后每个模块主体在依赖图的深度优先遍历中执行,通过跳过任何已经执行的内容来避免循环。

¥When you run a module containing an import declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.

ES6 深度:模块

¥– ES6 In Depth: Modules

用通俗的语言来说这是什么意思?这意味着你会认为以下内容可行,但实际上并非如此。

¥What does this mean in plain language? It means you would think the following would work but it won't.

errorReporter.mjs

import { Client } from 'best-error-reporting-service'

export default new Client(process.env.API_KEY)

index.mjs

// Note: this is INCORRECT and will not work
import * as dotenv from 'dotenv'
dotenv.config()

import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))

process.env.API_KEY 将为空白。

¥process.env.API_KEY will be blank.

相反,index.mjs 应该写成..

¥Instead, index.mjs should be written as..

import 'dotenv/config'

import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))

这有意义吗?这有点不直观,但这就是导入 ES6 模块的工作方式。这是一个 此陷阱的工作示例

¥Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a working example of this pitfall.

此方法有两种替代方法:

¥There are two alternatives to this approach:

  1. 预加载 dotenv:node --require dotenv/config index.js(注意:使用此方法不需要 import dotenv)

    ¥Preload dotenv: node --require dotenv/config index.js (Note: you do not need to import dotenv with this approach)

  2. 创建一个单独的文件,该文件将首先执行 config,如 #133 上的此评论 中所述

    ¥Create a separate file that will execute config first as outlined in this comment on #133

为什么我会收到错误 Module not found: Error: Can't resolve 'crypto|os|path'

¥Why am I getting the error Module not found: Error: Can't resolve 'crypto|os|path'?

你正在前端使用 dotenv,但未包含 polyfill。Webpack < 5 曾经为你包含这些。执行以下操作:

¥You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:

npm install node-polyfill-webpack-plugin

将你的 webpack.config.js 配置为类似以下内容。

¥Configure your webpack.config.js to something like the following.

require('dotenv').config()

const path = require('path');
const webpack = require('webpack')

const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')

module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};

或者,只需使用 dotenv-webpack 即可,它会在后台为你完成此操作和更多操作。

¥Alternatively, just use dotenv-webpack which does this and more behind the scenes for you.

如何扩展变量?

¥What about variable expansion?

尝试 dotenv-expand

¥Try dotenv-expand

如何同步和保护 .env 文件?

¥What about syncing and securing .env files?

使用 dotenvx

¥Use dotenvx

如果我不小心将 .env 文件提交到代码中会怎样?

¥What if I accidentally commit my .env file to code?

删除它,删除 git 历史记录,然后安装 git 预提交钩子 以防止这种情况再次发生。

¥Remove it, remove git history and then install the git pre-commit hook to prevent this from ever happening again.

brew install dotenvx/brew/dotenvx
dotenvx precommit --install

如何防止将我的 .env 文件提交到 Docker 构建?

¥How can I prevent committing my .env file to a Docker build?

使用 docker 预构建钩子

¥Use the docker prebuild hook.

# Dockerfile
...
RUN curl -fsS https://dotenvx.sh/ | sh
...
RUN dotenvx prebuild
CMD ["dotenvx", "run", "--", "node", "index.js"]

贡献指南

¥Contributing Guide

参见 CONTRIBUTING.md

¥See CONTRIBUTING.md

CHANGELOG

参见 CHANGELOG.md

¥See CHANGELOG.md

谁在使用 dotenv?

¥Who's using dotenv?

这些 npm 模块依赖于它。

¥These npm modules depend on it.

扩展它的项目通常使用 npm 上的关键字 "dotenv"

¥Projects that expand it often use the keyword "dotenv" on npm.