wrap-env 16.3.1 → 16.3.3
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +1 -633
- package/package.json +1 -1
- package/README-es.md +0 -442
package/README.md
CHANGED
@@ -1,633 +1 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
<p>
|
4
|
-
<sup>
|
5
|
-
<a href="https://github.com/sponsors/motdotla">Dotenv is supported by the community.</a>
|
6
|
-
</sup>
|
7
|
-
</p>
|
8
|
-
<sup>Special thanks to:</sup>
|
9
|
-
<br>
|
10
|
-
<br>
|
11
|
-
<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=dotenv_p_20220831">
|
12
|
-
<div>
|
13
|
-
<img src="https://res.cloudinary.com/dotenv-org/image/upload/v1661980709/warp_hi8oqj.png" width="230" alt="Warp">
|
14
|
-
</div>
|
15
|
-
<b>Warp is a blazingly fast, Rust-based terminal reimagined to work like a modern app.</b>
|
16
|
-
<div>
|
17
|
-
<sup>Get more done in the CLI with real text editing, block-based output, and AI command search.</sup>
|
18
|
-
</div>
|
19
|
-
</a>
|
20
|
-
<br>
|
21
|
-
<a href="https://retool.com/?utm_source=sponsor&utm_campaign=dotenv">
|
22
|
-
<div>
|
23
|
-
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_300/v1664466968/logo-full-black_vidfqf.png" width="270" alt="Retool">
|
24
|
-
</div>
|
25
|
-
<b>Retool helps developers build custom internal software, like CRUD apps and admin panels, really fast.</b>
|
26
|
-
<div>
|
27
|
-
<sup>Build UIs visually with flexible components, connect to any data source, and write business logic in JavaScript.</sup>
|
28
|
-
</div>
|
29
|
-
</a>
|
30
|
-
<br>
|
31
|
-
<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=dotenv&utm_source=github">
|
32
|
-
<div>
|
33
|
-
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_400/v1665605496/68747470733a2f2f73696e647265736f726875732e636f6d2f6173736574732f7468616e6b732f776f726b6f732d6c6f676f2d77686974652d62672e737667_zdmsbu.svg" width="270" alt="WorkOS">
|
34
|
-
</div>
|
35
|
-
<b>Your App, Enterprise Ready.</b>
|
36
|
-
<div>
|
37
|
-
<sup>Add Single Sign-On, Multi-Factor Auth, and more, in minutes instead of months.</sup>
|
38
|
-
</div>
|
39
|
-
</a>
|
40
|
-
<hr>
|
41
|
-
</div>
|
42
|
-
|
43
|
-
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
|
44
|
-
|
45
|
-
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
|
46
|
-
|
47
|
-
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](http://12factor.net/config) methodology.
|
48
|
-
|
49
|
-
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
|
50
|
-
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
|
51
|
-
[![dotenv-vault](https://badge.dotenv.org/works-with.svg?r=1)](https://www.dotenv.org/r/github.com/dotenv-org/dotenv-vault?r=1)
|
52
|
-
|
53
|
-
* [🌱 Install](#-install)
|
54
|
-
* [🏗️ Usage (.env)](#%EF%B8%8F-usage)
|
55
|
-
* [🚀 Deploying (.env.vault) 🆕](#-deploying)
|
56
|
-
* [🌴 Multiple Environments 🆕](#-manage-multiple-environments)
|
57
|
-
* [📚 Examples](#-examples)
|
58
|
-
* [📖 Docs](#-documentation)
|
59
|
-
* [❓ FAQ](#-faq)
|
60
|
-
* [⏱️ Changelog](./CHANGELOG.md)
|
61
|
-
|
62
|
-
## 🌱 Install
|
63
|
-
|
64
|
-
```bash
|
65
|
-
# install locally (recommended)
|
66
|
-
npm install dotenv --save
|
67
|
-
```
|
68
|
-
|
69
|
-
Or installing with yarn? `yarn add dotenv`
|
70
|
-
|
71
|
-
## 🏗️ Usage
|
72
|
-
|
73
|
-
<a href="https://www.youtube.com/watch?v=YtkZR0NFd1g">
|
74
|
-
<div align="right">
|
75
|
-
<img src="https://img.youtube.com/vi/YtkZR0NFd1g/hqdefault.jpg" alt="how to use dotenv video tutorial" align="right" width="330" />
|
76
|
-
<img src="https://simpleicons.vercel.app/youtube/ff0000" alt="youtube/@dotenvorg" align="right" width="24" />
|
77
|
-
</div>
|
78
|
-
</a>
|
79
|
-
|
80
|
-
Create a `.env` file in the root of your project:
|
81
|
-
|
82
|
-
```dosini
|
83
|
-
S3_BUCKET="YOURS3BUCKET"
|
84
|
-
SECRET_KEY="YOURSECRETKEYGOESHERE"
|
85
|
-
```
|
86
|
-
|
87
|
-
As early as possible in your application, import and configure dotenv:
|
88
|
-
|
89
|
-
```javascript
|
90
|
-
require('dotenv').config()
|
91
|
-
console.log(process.env) // remove this after you've confirmed it is working
|
92
|
-
```
|
93
|
-
|
94
|
-
.. [or using ES6?](#how-do-i-use-dotenv-with-import)
|
95
|
-
|
96
|
-
```javascript
|
97
|
-
import 'dotenv/config'
|
98
|
-
```
|
99
|
-
|
100
|
-
That's it. `process.env` now has the keys and values you defined in your `.env` file:
|
101
|
-
|
102
|
-
```javascript
|
103
|
-
require('dotenv').config()
|
104
|
-
|
105
|
-
...
|
106
|
-
|
107
|
-
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
|
108
|
-
```
|
109
|
-
|
110
|
-
### Multiline values
|
111
|
-
|
112
|
-
If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
|
113
|
-
|
114
|
-
```dosini
|
115
|
-
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
|
116
|
-
...
|
117
|
-
Kh9NV...
|
118
|
-
...
|
119
|
-
-----END RSA PRIVATE KEY-----"
|
120
|
-
```
|
121
|
-
|
122
|
-
Alternatively, you can double quote strings and use the `\n` character:
|
123
|
-
|
124
|
-
```dosini
|
125
|
-
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
|
126
|
-
```
|
127
|
-
|
128
|
-
### Comments
|
129
|
-
|
130
|
-
Comments may be added to your file on their own line or inline:
|
131
|
-
|
132
|
-
```dosini
|
133
|
-
# This is a comment
|
134
|
-
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
|
135
|
-
SECRET_HASH="something-with-a-#-hash"
|
136
|
-
```
|
137
|
-
|
138
|
-
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.
|
139
|
-
|
140
|
-
### Parsing
|
141
|
-
|
142
|
-
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.
|
143
|
-
|
144
|
-
```javascript
|
145
|
-
const dotenv = require('dotenv')
|
146
|
-
const buf = Buffer.from('BASIC=basic')
|
147
|
-
const config = dotenv.parse(buf) // will return an object
|
148
|
-
console.log(typeof config, config) // object { BASIC : 'basic' }
|
149
|
-
```
|
150
|
-
|
151
|
-
### Preload
|
152
|
-
|
153
|
-
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
|
154
|
-
|
155
|
-
```bash
|
156
|
-
$ node -r dotenv/config your_script.js
|
157
|
-
```
|
158
|
-
|
159
|
-
The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
|
160
|
-
|
161
|
-
```bash
|
162
|
-
$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
|
163
|
-
```
|
164
|
-
|
165
|
-
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
|
166
|
-
|
167
|
-
```bash
|
168
|
-
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
|
169
|
-
```
|
170
|
-
|
171
|
-
```bash
|
172
|
-
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
|
173
|
-
```
|
174
|
-
|
175
|
-
### Variable Expansion
|
176
|
-
|
177
|
-
You need to add the value of another variable in one of your variables? Use [dotenv-expand](https://github.com/motdotla/dotenv-expand).
|
178
|
-
|
179
|
-
### Syncing
|
180
|
-
|
181
|
-
You need to keep `.env` files in sync between machines, environments, or team members? Use [dotenv-vault](https://github.com/dotenv-org/dotenv-vault).
|
182
|
-
|
183
|
-
### Deploying
|
184
|
-
|
185
|
-
You need to deploy your secrets in a cloud-agnostic manner? Use a `.env.vault` file.
|
186
|
-
|
187
|
-
### Multiple Environments
|
188
|
-
|
189
|
-
You need to manage your secrets across different environments and apply them as needed? Use a `.env.vault` file with a `DOTENV_KEY`.
|
190
|
-
|
191
|
-
## 🚀 Deploying
|
192
|
-
|
193
|
-
*Note: Requires dotenv >= 16.1.0*
|
194
|
-
|
195
|
-
Encrypt your `.env.vault` file.
|
196
|
-
|
197
|
-
```bash
|
198
|
-
$ npx dotenv-vault build
|
199
|
-
```
|
200
|
-
|
201
|
-
Fetch your production `DOTENV_KEY`.
|
202
|
-
|
203
|
-
```bash
|
204
|
-
$ npx dotenv-vault keys production
|
205
|
-
```
|
206
|
-
|
207
|
-
Set `DOTENV_KEY` on your server.
|
208
|
-
|
209
|
-
```bash
|
210
|
-
# heroku example
|
211
|
-
heroku config:set DOTENV_KEY=dotenv://:key_1234…@dotenv.org/vault/.env.vault?environment=production
|
212
|
-
```
|
213
|
-
|
214
|
-
That's it! On deploy, your `.env.vault` file will be decrypted and its secrets injected as environment variables – just in time.
|
215
|
-
|
216
|
-
*ℹ️ A note from [Mot](https://github.com/motdotla): Until recently, we did not have an opinion on how and where to store your secrets in production. We now strongly recommend generating a `.env.vault` file. It's the best way to prevent your secrets from being scattered across multiple servers and cloud providers – protecting you from breaches like the [CircleCI breach](https://techcrunch.com/2023/01/05/circleci-breach/). Also it unlocks interoperability WITHOUT native third-party integrations. Third-party integrations are [increasingly risky](https://coderpad.io/blog/development/heroku-github-breach/) to our industry. They may be the 'du jour' of today, but we imagine a better future.*
|
217
|
-
|
218
|
-
<a href="https://github.com/dotenv-org/dotenv-vault#dotenv-vault-">Learn more at dotenv-vault: Deploying</a>
|
219
|
-
|
220
|
-
## 🌴 Manage Multiple Environments
|
221
|
-
|
222
|
-
Edit your production environment variables.
|
223
|
-
|
224
|
-
```bash
|
225
|
-
$ npx dotenv-vault open production
|
226
|
-
```
|
227
|
-
|
228
|
-
Regenerate your `.env.vault` file.
|
229
|
-
|
230
|
-
```bash
|
231
|
-
$ npx dotenv-vault build
|
232
|
-
```
|
233
|
-
|
234
|
-
*ℹ️ 🔐 Vault Managed vs 💻 Locally Managed: The above example, for brevity's sake, used the 🔐 Vault Managed solution to manage your `.env.vault` file. You can instead use the 💻 Locally Managed solution. [Read more here](https://github.com/dotenv-org/dotenv-vault#how-do-i-use--locally-managed-dotenv-vault). Our vision is that other platforms and orchestration tools adopt the `.env.vault` standard as they did the `.env` standard. We don't expect to be the only ones providing tooling to manage and generate `.env.vault` files.*
|
235
|
-
|
236
|
-
<a href="https://github.com/dotenv-org/dotenv-vault#-manage-multiple-environments">Learn more at dotenv-vault: Manage Multiple Environments</a>
|
237
|
-
|
238
|
-
## 📚 Examples
|
239
|
-
|
240
|
-
See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
|
241
|
-
|
242
|
-
* [nodejs](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs)
|
243
|
-
* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-debug)
|
244
|
-
* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-override)
|
245
|
-
* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/dotenv-custom-target)
|
246
|
-
* [nodejs (DOTENV_KEY override)](https://github.com/dotenv-org/examples/tree/master/dotenv-vault-custom-target)
|
247
|
-
* [esm](https://github.com/dotenv-org/examples/tree/master/dotenv-esm)
|
248
|
-
* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/dotenv-esm-preload)
|
249
|
-
* [typescript](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript)
|
250
|
-
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-parse)
|
251
|
-
* [typescript config](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-config)
|
252
|
-
* [webpack](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack)
|
253
|
-
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack2)
|
254
|
-
* [react](https://github.com/dotenv-org/examples/tree/master/dotenv-react)
|
255
|
-
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/dotenv-react-typescript)
|
256
|
-
* [express](https://github.com/dotenv-org/examples/tree/master/dotenv-express)
|
257
|
-
* [nestjs](https://github.com/dotenv-org/examples/tree/master/dotenv-nestjs)
|
258
|
-
* [fastify](https://github.com/dotenv-org/examples/tree/master/dotenv-fastify)
|
259
|
-
|
260
|
-
## 📖 Documentation
|
261
|
-
|
262
|
-
Dotenv exposes four functions:
|
263
|
-
|
264
|
-
* `config`
|
265
|
-
* `parse`
|
266
|
-
* `populate`
|
267
|
-
* `decrypt`
|
268
|
-
|
269
|
-
### Config
|
270
|
-
|
271
|
-
`config` will read your `.env` file, parse the contents, assign it to
|
272
|
-
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
|
273
|
-
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
|
274
|
-
|
275
|
-
```js
|
276
|
-
const result = dotenv.config()
|
277
|
-
|
278
|
-
if (result.error) {
|
279
|
-
throw result.error
|
280
|
-
}
|
281
|
-
|
282
|
-
console.log(result.parsed)
|
283
|
-
```
|
284
|
-
|
285
|
-
You can additionally, pass options to `config`.
|
286
|
-
|
287
|
-
#### Options
|
288
|
-
|
289
|
-
##### path
|
290
|
-
|
291
|
-
Default: `path.resolve(process.cwd(), '.env')`
|
292
|
-
|
293
|
-
Specify a custom path if your file containing environment variables is located elsewhere.
|
294
|
-
|
295
|
-
```js
|
296
|
-
require('dotenv').config({ path: '/custom/path/to/.env' })
|
297
|
-
```
|
298
|
-
|
299
|
-
##### encoding
|
300
|
-
|
301
|
-
Default: `utf8`
|
302
|
-
|
303
|
-
Specify the encoding of your file containing environment variables.
|
304
|
-
|
305
|
-
```js
|
306
|
-
require('dotenv').config({ encoding: 'latin1' })
|
307
|
-
```
|
308
|
-
|
309
|
-
##### debug
|
310
|
-
|
311
|
-
Default: `false`
|
312
|
-
|
313
|
-
Turn on logging to help debug why certain keys or values are not being set as you expect.
|
314
|
-
|
315
|
-
```js
|
316
|
-
require('dotenv').config({ debug: process.env.DEBUG })
|
317
|
-
```
|
318
|
-
|
319
|
-
##### override
|
320
|
-
|
321
|
-
Default: `false`
|
322
|
-
|
323
|
-
Override any environment variables that have already been set on your machine with values from your .env file.
|
324
|
-
|
325
|
-
```js
|
326
|
-
require('dotenv').config({ override: true })
|
327
|
-
```
|
328
|
-
|
329
|
-
##### processEnv
|
330
|
-
|
331
|
-
Default: `process.env`
|
332
|
-
|
333
|
-
Specify an object to write your secrets to. Defaults to `process.env` environment variables.
|
334
|
-
|
335
|
-
```js
|
336
|
-
const myObject = {}
|
337
|
-
require('dotenv').config({ processEnv: myObject })
|
338
|
-
|
339
|
-
console.log(myObject) // values from .env or .env.vault live here now.
|
340
|
-
console.log(process.env) // this was not changed or written to
|
341
|
-
```
|
342
|
-
|
343
|
-
##### DOTENV_KEY
|
344
|
-
|
345
|
-
Default: `process.env.DOTENV_KEY`
|
346
|
-
|
347
|
-
Pass the `DOTENV_KEY` directly to config options. Defaults to looking for `process.env.DOTENV_KEY` environment variable. Note this only applies to decrypting `.env.vault` files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a `.env` file.
|
348
|
-
|
349
|
-
```js
|
350
|
-
require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenv.org/vault/.env.vault?environment=production' })
|
351
|
-
```
|
352
|
-
|
353
|
-
### Parse
|
354
|
-
|
355
|
-
The engine which parses the contents of your file containing environment
|
356
|
-
variables is available to use. It accepts a String or Buffer and will return
|
357
|
-
an Object with the parsed keys and values.
|
358
|
-
|
359
|
-
```js
|
360
|
-
const dotenv = require('dotenv')
|
361
|
-
const buf = Buffer.from('BASIC=basic')
|
362
|
-
const config = dotenv.parse(buf) // will return an object
|
363
|
-
console.log(typeof config, config) // object { BASIC : 'basic' }
|
364
|
-
```
|
365
|
-
|
366
|
-
#### Options
|
367
|
-
|
368
|
-
##### debug
|
369
|
-
|
370
|
-
Default: `false`
|
371
|
-
|
372
|
-
Turn on logging to help debug why certain keys or values are not being set as you expect.
|
373
|
-
|
374
|
-
```js
|
375
|
-
const dotenv = require('dotenv')
|
376
|
-
const buf = Buffer.from('hello world')
|
377
|
-
const opt = { debug: true }
|
378
|
-
const config = dotenv.parse(buf, opt)
|
379
|
-
// expect a debug message because the buffer is not in KEY=VAL form
|
380
|
-
```
|
381
|
-
|
382
|
-
### Populate
|
383
|
-
|
384
|
-
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.
|
385
|
-
|
386
|
-
For example, customizing the source:
|
387
|
-
|
388
|
-
```js
|
389
|
-
const dotenv = require('dotenv')
|
390
|
-
const parsed = { HELLO: 'world' }
|
391
|
-
|
392
|
-
dotenv.populate(process.env, parsed)
|
393
|
-
|
394
|
-
console.log(process.env.HELLO) // world
|
395
|
-
```
|
396
|
-
|
397
|
-
For example, customizing the source AND target:
|
398
|
-
|
399
|
-
```js
|
400
|
-
const dotenv = require('dotenv')
|
401
|
-
const parsed = { HELLO: 'universe' }
|
402
|
-
const target = { HELLO: 'world' } // empty object
|
403
|
-
|
404
|
-
dotenv.populate(target, parsed, { override: true, debug: true })
|
405
|
-
|
406
|
-
console.log(target) // { HELLO: 'universe' }
|
407
|
-
```
|
408
|
-
|
409
|
-
#### options
|
410
|
-
|
411
|
-
##### Debug
|
412
|
-
|
413
|
-
Default: `false`
|
414
|
-
|
415
|
-
Turn on logging to help debug why certain keys or values are not being populated as you expect.
|
416
|
-
|
417
|
-
##### override
|
418
|
-
|
419
|
-
Default: `false`
|
420
|
-
|
421
|
-
Override any environment variables that have already been set.
|
422
|
-
|
423
|
-
### Decrypt
|
424
|
-
|
425
|
-
The engine which decrypts the ciphertext contents of your .env.vault file is available for use. It accepts a ciphertext and a decryption key. It uses AES-256-GCM encryption.
|
426
|
-
|
427
|
-
For example, decrypting a simple ciphertext:
|
428
|
-
|
429
|
-
```js
|
430
|
-
const dotenv = require('dotenv')
|
431
|
-
const ciphertext = 's7NYXa809k/bVSPwIAmJhPJmEGTtU0hG58hOZy7I0ix6y5HP8LsHBsZCYC/gw5DDFy5DgOcyd18R'
|
432
|
-
const decryptionKey = 'ddcaa26504cd70a6fef9801901c3981538563a1767c297cb8416e8a38c62fe00'
|
433
|
-
|
434
|
-
const decrypted = dotenv.decrypt(ciphertext, decryptionKey)
|
435
|
-
|
436
|
-
console.log(decrypted) // # development@v6\nALPHA="zeta"
|
437
|
-
```
|
438
|
-
|
439
|
-
## ❓ FAQ
|
440
|
-
|
441
|
-
### Why is the `.env` file not loading my environment variables successfully?
|
442
|
-
|
443
|
-
Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
|
444
|
-
|
445
|
-
Turn on debug mode and try again..
|
446
|
-
|
447
|
-
```js
|
448
|
-
require('dotenv').config({ debug: true })
|
449
|
-
```
|
450
|
-
|
451
|
-
You will receive a helpful error outputted to your console.
|
452
|
-
|
453
|
-
### Should I commit my `.env` file?
|
454
|
-
|
455
|
-
No. We **strongly** recommend against committing your `.env` file to version
|
456
|
-
control. It should only include environment-specific values such as database
|
457
|
-
passwords or API keys. Your production database should have a different
|
458
|
-
password than your development database.
|
459
|
-
|
460
|
-
### Should I have multiple `.env` files?
|
461
|
-
|
462
|
-
No. We **strongly** recommend against having a "main" `.env` file and an "environment" `.env` file like `.env.test`. Your config should vary between deploys, and you should not be sharing values between environments.
|
463
|
-
|
464
|
-
> 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.
|
465
|
-
>
|
466
|
-
> – [The Twelve-Factor App](http://12factor.net/config)
|
467
|
-
|
468
|
-
### What rules does the parsing engine follow?
|
469
|
-
|
470
|
-
The parsing engine currently supports the following rules:
|
471
|
-
|
472
|
-
- `BASIC=basic` becomes `{BASIC: 'basic'}`
|
473
|
-
- empty lines are skipped
|
474
|
-
- lines beginning with `#` are treated as comments
|
475
|
-
- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
|
476
|
-
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
|
477
|
-
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
|
478
|
-
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
|
479
|
-
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
|
480
|
-
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
|
481
|
-
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
|
482
|
-
|
483
|
-
```
|
484
|
-
{MULTILINE: 'new
|
485
|
-
line'}
|
486
|
-
```
|
487
|
-
|
488
|
-
- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
|
489
|
-
|
490
|
-
### What happens to environment variables that were already set?
|
491
|
-
|
492
|
-
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.
|
493
|
-
|
494
|
-
If instead, you want to override `process.env` use the `override` option.
|
495
|
-
|
496
|
-
```javascript
|
497
|
-
require('dotenv').config({ override: true })
|
498
|
-
```
|
499
|
-
|
500
|
-
### How come my environment variables are not showing up for React?
|
501
|
-
|
502
|
-
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.
|
503
|
-
|
504
|
-
If you are using [`react-scripts`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) for more details.
|
505
|
-
|
506
|
-
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.
|
507
|
-
|
508
|
-
### Can I customize/write plugins for dotenv?
|
509
|
-
|
510
|
-
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:
|
511
|
-
|
512
|
-
```js
|
513
|
-
const dotenv = require('dotenv')
|
514
|
-
const variableExpansion = require('dotenv-expand')
|
515
|
-
const myEnv = dotenv.config()
|
516
|
-
variableExpansion(myEnv)
|
517
|
-
```
|
518
|
-
|
519
|
-
### How do I use dotenv with `import`?
|
520
|
-
|
521
|
-
Simply..
|
522
|
-
|
523
|
-
```javascript
|
524
|
-
// index.mjs (ESM)
|
525
|
-
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
|
526
|
-
import express from 'express'
|
527
|
-
```
|
528
|
-
|
529
|
-
A little background..
|
530
|
-
|
531
|
-
> 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.
|
532
|
-
>
|
533
|
-
> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
|
534
|
-
|
535
|
-
What does this mean in plain language? It means you would think the following would work but it won't.
|
536
|
-
|
537
|
-
`errorReporter.mjs`:
|
538
|
-
```js
|
539
|
-
import { Client } from 'best-error-reporting-service'
|
540
|
-
|
541
|
-
export default new Client(process.env.API_KEY)
|
542
|
-
```
|
543
|
-
`index.mjs`:
|
544
|
-
```js
|
545
|
-
// Note: this is INCORRECT and will not work
|
546
|
-
import * as dotenv from 'dotenv'
|
547
|
-
dotenv.config()
|
548
|
-
|
549
|
-
import errorReporter from './errorReporter.mjs'
|
550
|
-
errorReporter.report(new Error('documented example'))
|
551
|
-
```
|
552
|
-
|
553
|
-
`process.env.API_KEY` will be blank.
|
554
|
-
|
555
|
-
Instead, `index.mjs` should be written as..
|
556
|
-
|
557
|
-
```js
|
558
|
-
import 'dotenv/config'
|
559
|
-
|
560
|
-
import errorReporter from './errorReporter.mjs'
|
561
|
-
errorReporter.report(new Error('documented example'))
|
562
|
-
```
|
563
|
-
|
564
|
-
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](https://github.com/dotenv-org/examples/tree/master/dotenv-es6-import-pitfall).
|
565
|
-
|
566
|
-
There are two alternatives to this approach:
|
567
|
-
|
568
|
-
1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
|
569
|
-
2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
|
570
|
-
|
571
|
-
### Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
|
572
|
-
|
573
|
-
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:
|
574
|
-
|
575
|
-
```bash
|
576
|
-
npm install node-polyfill-webpack-plugin
|
577
|
-
```
|
578
|
-
|
579
|
-
Configure your `webpack.config.js` to something like the following.
|
580
|
-
|
581
|
-
```js
|
582
|
-
require('dotenv').config()
|
583
|
-
|
584
|
-
const path = require('path');
|
585
|
-
const webpack = require('webpack')
|
586
|
-
|
587
|
-
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
|
588
|
-
|
589
|
-
module.exports = {
|
590
|
-
mode: 'development',
|
591
|
-
entry: './src/index.ts',
|
592
|
-
output: {
|
593
|
-
filename: 'bundle.js',
|
594
|
-
path: path.resolve(__dirname, 'dist'),
|
595
|
-
},
|
596
|
-
plugins: [
|
597
|
-
new NodePolyfillPlugin(),
|
598
|
-
new webpack.DefinePlugin({
|
599
|
-
'process.env': {
|
600
|
-
HELLO: JSON.stringify(process.env.HELLO)
|
601
|
-
}
|
602
|
-
}),
|
603
|
-
]
|
604
|
-
};
|
605
|
-
```
|
606
|
-
|
607
|
-
Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
|
608
|
-
|
609
|
-
### What about variable expansion?
|
610
|
-
|
611
|
-
Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
|
612
|
-
|
613
|
-
### What about syncing and securing .env files?
|
614
|
-
|
615
|
-
Use [dotenv-vault](https://github.com/dotenv-org/dotenv-vault)
|
616
|
-
|
617
|
-
### What is a `.env.vault` file?
|
618
|
-
|
619
|
-
A `.env.vault` file is an encrypted version of your development (and ci, staging, production, etc) environment variables. It is paired with a `DOTENV_KEY` to deploy your secrets more securely than scattering them across multiple platforms and tools. Use [dotenv-vault](https://github.com/dotenv-org/dotenv-vault) to manage and generate them.
|
620
|
-
|
621
|
-
## Contributing Guide
|
622
|
-
|
623
|
-
See [CONTRIBUTING.md](CONTRIBUTING.md)
|
624
|
-
|
625
|
-
## CHANGELOG
|
626
|
-
|
627
|
-
See [CHANGELOG.md](CHANGELOG.md)
|
628
|
-
|
629
|
-
## Who's using dotenv?
|
630
|
-
|
631
|
-
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
|
632
|
-
|
633
|
-
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).
|
1
|
+
This package is an wrap of `dotenv`
|
package/package.json
CHANGED
package/README-es.md
DELETED
@@ -1,442 +0,0 @@
|
|
1
|
-
<div align="center">
|
2
|
-
|
3
|
-
<p>
|
4
|
-
<sup>
|
5
|
-
<a href="https://github.com/sponsors/motdotla">Dotenv es apoyado por la comunidad.</a>
|
6
|
-
</sup>
|
7
|
-
</p>
|
8
|
-
<sup>Gracias espaciales a:</sup>
|
9
|
-
<br>
|
10
|
-
<br>
|
11
|
-
<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=dotenv_p_20220831">
|
12
|
-
<div>
|
13
|
-
<img src="https://res.cloudinary.com/dotenv-org/image/upload/v1661980709/warp_hi8oqj.png" width="230" alt="Warp">
|
14
|
-
</div>
|
15
|
-
<b>Warp es una rápida e impresionante terminal basada en Rust, reinventado para funcionar como una aplicación moderna.</b>
|
16
|
-
<div>
|
17
|
-
<sup>Haga más en la CLI con edición de texto real, resultado básado en bloques, y busqueda de comandos de IA.</sup>
|
18
|
-
</div>
|
19
|
-
</a>
|
20
|
-
<br>
|
21
|
-
<a href="https://retool.com/?utm_source=sponsor&utm_campaign=dotenv">
|
22
|
-
<div>
|
23
|
-
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_300/v1664466968/logo-full-black_vidfqf.png" width="270" alt="Retool">
|
24
|
-
</div>
|
25
|
-
<b>Retool ayuda a los desarrolladores a crear software interno personalizado, como aplicaciones CRUD y paneles de administración, realmente rápido.</b>
|
26
|
-
<div>
|
27
|
-
<sup>Construya Interfaces de Usuario de forma visual con componentes flexibles, conéctese a cualquier fuente de datos, y escriba lógica de negocio en JavaScript.</sup>
|
28
|
-
</div>
|
29
|
-
</a>
|
30
|
-
<br>
|
31
|
-
<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=dotenv&utm_source=github">
|
32
|
-
<div>
|
33
|
-
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_400/v1665605496/68747470733a2f2f73696e647265736f726875732e636f6d2f6173736574732f7468616e6b732f776f726b6f732d6c6f676f2d77686974652d62672e737667_zdmsbu.svg" width="270" alt="WorkOS">
|
34
|
-
</div>
|
35
|
-
<b>Su Apliación, Lista para la Empresa.</b>
|
36
|
-
<div>
|
37
|
-
<sup>Agrega Inicio de Sesión Único, Autenticación Multi-Factor, y mucho más, en minutos en lugar de meses.</sup>
|
38
|
-
</div>
|
39
|
-
</a>
|
40
|
-
<hr>
|
41
|
-
<br>
|
42
|
-
<br>
|
43
|
-
<br>
|
44
|
-
<br>
|
45
|
-
|
46
|
-
</div>
|
47
|
-
|
48
|
-
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
|
49
|
-
|
50
|
-
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
|
51
|
-
|
52
|
-
Dotenv es un módulo de dependencia cero que carga las variables de entorno desde un archivo `.env` en [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). El almacenamiento de la configuración del entorno separado del código está basado en la metodología [The Twelve-Factor App](http://12factor.net/config).
|
53
|
-
|
54
|
-
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
|
55
|
-
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
|
56
|
-
|
57
|
-
## Instalación
|
58
|
-
|
59
|
-
```bash
|
60
|
-
# instalación local (recomendado)
|
61
|
-
npm install dotenv --save
|
62
|
-
```
|
63
|
-
|
64
|
-
O installación con yarn? `yarn add dotenv`
|
65
|
-
|
66
|
-
## Uso
|
67
|
-
|
68
|
-
Cree un archivo `.env` en la raíz de su proyecto:
|
69
|
-
|
70
|
-
```dosini
|
71
|
-
S3_BUCKET="YOURS3BUCKET"
|
72
|
-
SECRET_KEY="YOURSECRETKEYGOESHERE"
|
73
|
-
```
|
74
|
-
|
75
|
-
Tan prónto como sea posible en su aplicación, importe y configure dotenv:
|
76
|
-
|
77
|
-
```javascript
|
78
|
-
require('dotenv').config()
|
79
|
-
console.log(process.env) // elimine esto después que haya confirmado que esta funcionando
|
80
|
-
```
|
81
|
-
|
82
|
-
.. o usa ES6?
|
83
|
-
|
84
|
-
```javascript
|
85
|
-
import * as dotenv from 'dotenv' // vea en https://github.com/motdotla/dotenv#como-uso-dotenv-con-import
|
86
|
-
// REVISAR LINK DE REFERENCIA DE IMPORTACIÓN
|
87
|
-
dotenv.config()
|
88
|
-
import express from 'express'
|
89
|
-
```
|
90
|
-
|
91
|
-
Eso es todo. `process.env` ahora tiene las claves y los valores que definiste en tu archivo `.env`:
|
92
|
-
|
93
|
-
```javascript
|
94
|
-
require('dotenv').config()
|
95
|
-
|
96
|
-
...
|
97
|
-
|
98
|
-
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
|
99
|
-
```
|
100
|
-
|
101
|
-
### Valores multilínea
|
102
|
-
|
103
|
-
Si necesita variables de varias líneas, por ejemplo, claves privadas, ahora se admiten en la versión (`>= v15.0.0`) con saltos de línea:
|
104
|
-
|
105
|
-
```dosini
|
106
|
-
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
|
107
|
-
...
|
108
|
-
Kh9NV...
|
109
|
-
...
|
110
|
-
-----END RSA PRIVATE KEY-----"
|
111
|
-
```
|
112
|
-
|
113
|
-
Alternativamente, puede usar comillas dobles y usar el carácter `\n`:
|
114
|
-
|
115
|
-
```dosini
|
116
|
-
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
|
117
|
-
```
|
118
|
-
|
119
|
-
### Comentarios
|
120
|
-
|
121
|
-
Los comentarios pueden ser agregados en tu archivo o en la misma línea:
|
122
|
-
|
123
|
-
```dosini
|
124
|
-
# This is a comment
|
125
|
-
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
|
126
|
-
SECRET_HASH="something-with-a-#-hash"
|
127
|
-
```
|
128
|
-
|
129
|
-
Los comentarios comienzan donde existe un `#`, entonces, si su valor contiene un `#`, enciérrelo entre comillas. Este es un cambio importante desde la versión `>= v15.0.0` en adelante.
|
130
|
-
|
131
|
-
### Análisis
|
132
|
-
|
133
|
-
El motor que analiza el contenido de su archivo que contiene variables de entorno está disponible para su uso. Este Acepta una Cadena o un Búfer y devolverá un Objeto con las claves y los valores analizados.
|
134
|
-
|
135
|
-
```javascript
|
136
|
-
const dotenv = require('dotenv')
|
137
|
-
const buf = Buffer.from('BASICO=basico')
|
138
|
-
const config = dotenv.parse(buf) // devolverá un objeto
|
139
|
-
console.log(typeof config, config) // objeto { BASICO : 'basico' }
|
140
|
-
```
|
141
|
-
|
142
|
-
### Precarga
|
143
|
-
|
144
|
-
Puede usar el `--require` (`-r`) [opción de línea de comando](https://nodejs.org/api/cli.html#-r---require-module) para precargar dotenv. Al hacer esto, no necesita requerir ni cargar dotnev en el código de su aplicación.
|
145
|
-
|
146
|
-
```bash
|
147
|
-
$ node -r dotenv/config tu_script.js
|
148
|
-
```
|
149
|
-
|
150
|
-
Las opciones de configuración a continuación se admiten como argumentos de línea de comandos en el formato `dotenv_config_<option>=value`
|
151
|
-
|
152
|
-
```bash
|
153
|
-
$ node -r dotenv/config tu_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
|
154
|
-
```
|
155
|
-
|
156
|
-
Además, puede usar variables de entorno para establecer opciones de configuración. Los argumentos de línea de comandos precederán a estos.
|
157
|
-
|
158
|
-
```bash
|
159
|
-
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config tu_script.js
|
160
|
-
```
|
161
|
-
|
162
|
-
```bash
|
163
|
-
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config tu_script.js dotenv_config_path=/custom/path/to/.env
|
164
|
-
```
|
165
|
-
|
166
|
-
### Expansión Variable
|
167
|
-
|
168
|
-
Necesitaras agregar el valor de otro variable en una de sus variables? Usa [dotenv-expand](https://github.com/motdotla/dotenv-expand).
|
169
|
-
|
170
|
-
### Sincronizando
|
171
|
-
|
172
|
-
Necesitas mentener sincronizados los archivos `.env` entre maquinas, entornos, o miembros del equipo? Usa
|
173
|
-
[dotenv-vault](https://github.com/dotenv-org/dotenv-vault).
|
174
|
-
|
175
|
-
## Ejemplos
|
176
|
-
|
177
|
-
Vea [ejemplos](https://github.com/dotenv-org/examples) sobre el uso de dotenv con varios frameworks, lenguajes y configuraciones.
|
178
|
-
|
179
|
-
* [nodejs](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs)
|
180
|
-
* [nodejs (depurar en)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-debug)
|
181
|
-
* [nodejs (anular en)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-override)
|
182
|
-
* [esm](https://github.com/dotenv-org/examples/tree/master/dotenv-esm)
|
183
|
-
* [esm (precarga)](https://github.com/dotenv-org/examples/tree/master/dotenv-esm-preload)
|
184
|
-
* [typescript](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript)
|
185
|
-
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-parse)
|
186
|
-
* [typescript config](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-config)
|
187
|
-
* [webpack](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack)
|
188
|
-
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack2)
|
189
|
-
* [react](https://github.com/dotenv-org/examples/tree/master/dotenv-react)
|
190
|
-
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/dotenv-react-typescript)
|
191
|
-
* [express](https://github.com/dotenv-org/examples/tree/master/dotenv-express)
|
192
|
-
* [nestjs](https://github.com/dotenv-org/examples/tree/master/dotenv-nestjs)
|
193
|
-
|
194
|
-
## Documentación
|
195
|
-
|
196
|
-
Dotenv expone dos funciones:
|
197
|
-
|
198
|
-
* `configuración`
|
199
|
-
* `analizar`
|
200
|
-
|
201
|
-
### Configuración
|
202
|
-
|
203
|
-
`Configuración` leerá su archivo `.env`, analizará el contenido, lo asignará a [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
|
204
|
-
y devolverá un Objeto con una clave `parsed` que contiene el contenido cargado o una clave `error` si falla.
|
205
|
-
|
206
|
-
```js
|
207
|
-
const result = dotenv.config()
|
208
|
-
|
209
|
-
if (result.error) {
|
210
|
-
throw result.error
|
211
|
-
}
|
212
|
-
|
213
|
-
console.log(result.parsed)
|
214
|
-
```
|
215
|
-
|
216
|
-
Adicionalmente, puede pasar opciones a `configuracion`.
|
217
|
-
|
218
|
-
#### Opciones
|
219
|
-
|
220
|
-
##### Ruta
|
221
|
-
|
222
|
-
Por defecto: `path.resolve(process.cwd(), '.env')`
|
223
|
-
|
224
|
-
Especifique una ruta personalizada si el archivo que contiene las variables de entorno se encuentra localizado en otro lugar.
|
225
|
-
|
226
|
-
```js
|
227
|
-
require('dotenv').config({ path: '/personalizado/ruta/a/.env' })
|
228
|
-
```
|
229
|
-
|
230
|
-
##### Codificación
|
231
|
-
|
232
|
-
Por defecto: `utf8`
|
233
|
-
|
234
|
-
Especifique la codificación del archivo que contiene las variables de entorno.
|
235
|
-
|
236
|
-
```js
|
237
|
-
require('dotenv').config({ encoding: 'latin1' })
|
238
|
-
```
|
239
|
-
|
240
|
-
##### Depurar
|
241
|
-
|
242
|
-
Por defecto: `false`
|
243
|
-
|
244
|
-
Active el registro de ayuda para depurar por qué ciertas claves o valores no se inician como lo esperabas.
|
245
|
-
|
246
|
-
```js
|
247
|
-
require('dotenv').config({ debug: process.env.DEBUG })
|
248
|
-
```
|
249
|
-
|
250
|
-
##### Anular
|
251
|
-
|
252
|
-
Por defecto: `false`
|
253
|
-
|
254
|
-
Anule cualquier variable de entorno que ya se haya configurada en su maquina con los valores de su archivo .env.
|
255
|
-
|
256
|
-
```js
|
257
|
-
require('dotenv').config({ override: true })
|
258
|
-
```
|
259
|
-
|
260
|
-
### Analizar
|
261
|
-
|
262
|
-
El motor que analiza el contenido del archivo que contiene las variables de entorno está disponible para su uso. Acepta una Cadena o un Búfer y retornará un objecto con los valores analizados.
|
263
|
-
|
264
|
-
```js
|
265
|
-
const dotenv = require('dotenv')
|
266
|
-
const buf = Buffer.from('BASICO=basico')
|
267
|
-
const config = dotenv.parse(buf) // devolverá un objeto
|
268
|
-
console.log(typeof config, config) // objeto { BASICO : 'basico' }
|
269
|
-
```
|
270
|
-
|
271
|
-
#### Opciones
|
272
|
-
|
273
|
-
##### Depurar
|
274
|
-
|
275
|
-
Por defecto: `false`
|
276
|
-
|
277
|
-
Active el registro de ayuda para depurar por qué ciertas claves o valores no se inician como lo esperabas.
|
278
|
-
|
279
|
-
```js
|
280
|
-
const dotenv = require('dotenv')
|
281
|
-
const buf = Buffer.from('hola mundo')
|
282
|
-
const opt = { debug: true }
|
283
|
-
const config = dotenv.parse(buf, opt)
|
284
|
-
// espere por un mensaje de depuración porque el búfer no esta listo KEY=VAL
|
285
|
-
```
|
286
|
-
|
287
|
-
## FAQ
|
288
|
-
|
289
|
-
### ¿Por qué el archivo `.env` no carga mis variables de entorno correctamente?
|
290
|
-
|
291
|
-
Lo más probable es que su archivo `.env` no esté en el lugar correcto. [Vea este stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
|
292
|
-
|
293
|
-
Active el modo de depuración y vuelva a intentarlo...
|
294
|
-
|
295
|
-
```js
|
296
|
-
require('dotenv').config({ debug: true })
|
297
|
-
```
|
298
|
-
|
299
|
-
Recibirá un error apropiado en su consola.
|
300
|
-
|
301
|
-
### ¿Debo confirmar mi archivo `.env`?
|
302
|
-
|
303
|
-
No. Recomendamos **enfáticamente** no enviar su archivo `.env` a la versión de control. Solo debe incluir los valores especificos del entorno, como la base de datos, contraseñas o claves API.
|
304
|
-
|
305
|
-
### ¿Debería tener multiples archivos `.env`?
|
306
|
-
|
307
|
-
No. Recomendamos **enfáticamente** no tener un archivo `.env` "principal" y un archivo `.env` de "entorno" como `.env.test`. Su configuración debe variar entre implementaciones y no debe compartir valores entre entornos.
|
308
|
-
|
309
|
-
> En una Aplicación de Doce Factores, las variables de entorno son controles diferenciados, cada uno totalmente independiente a otras variables de entorno. Nunca se agrupan como "entornos", sino que se gestionan de manera independiente para cada despliegue. Este es un modelo que se escala sin problemas a medida que la aplicación se expande de forma natural en más despliegues a lo largo de su vida.
|
310
|
-
>
|
311
|
-
> – [La Apliación de los Doce Factores](https://12factor.net/es/)
|
312
|
-
|
313
|
-
### ¿Qué reglas sigue el motor de análisis?
|
314
|
-
|
315
|
-
El motor de análisis actualmente admite las siguientes reglas:
|
316
|
-
|
317
|
-
- `BASICO=basico` se convierte en `{BASICO: 'basico'}`
|
318
|
-
- las líneas vacías se saltan
|
319
|
-
- las líneas que comienzan con `#` se tratan como comentarios
|
320
|
-
- `#` marca el comienzo de un comentario (a menos que el valor esté entre comillas)
|
321
|
-
- valores vacíos se convierten en cadenas vacías (`VACIO=` se convierte en `{VACIO: ''}`)
|
322
|
-
- las comillas internas se mantienen (piensa en JSON) (`JSON={"foo": "bar"}` se convierte en `{JSON:"{\"foo\": \"bar\"}"`)
|
323
|
-
- los espacios en blanco se eliminan de ambos extremos de los valores no citanos (aprende más en [`trim`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= algo ` se convierte en `{FOO: 'algo'}`)
|
324
|
-
- los valores entre comillas simples y dobles se escapan (`CITA_SIMPLE='citado'` se convierte en `{CITA_SIMPLE: "citado"}`)
|
325
|
-
- los valores entre comillas simples y dobles mantienen los espacios en blanco en ambos extremos (`FOO=" algo "` se convierte en `{FOO: ' algo '}`)
|
326
|
-
- los valores entre comillas dobles expanden nuevas líneas (`MULTILINEA="nueva\nlínea"` se convierte en
|
327
|
-
|
328
|
-
```
|
329
|
-
{MULTILINEA: 'nueva
|
330
|
-
línea'}
|
331
|
-
```
|
332
|
-
|
333
|
-
- se admite la comilla simple invertida (`` SIGNO_ACENTO=`Esto tiene comillas 'simples' y "dobles" en su interior.` ``)
|
334
|
-
|
335
|
-
### ¿Qué sucede con las variables de entorno que ya estaban configuradas?
|
336
|
-
|
337
|
-
Por defecto, nunca modificaremos ninguna variable de entorno que ya haya sido establecida. En particular, si hay una variable en su archivo `.env` que colisiona con una que ya existe en su entorno, entonces esa variable se omitirá.
|
338
|
-
|
339
|
-
Si por el contrario, quieres anular `process.env` utiliza la opción `override`.
|
340
|
-
|
341
|
-
```javascript
|
342
|
-
require('dotenv').config({ override: true })
|
343
|
-
```
|
344
|
-
|
345
|
-
### ¿Por qué mis variables de entorno no aparecen para React?
|
346
|
-
|
347
|
-
Su código React se ejecuta en Webpack, donde el módulo `fs` o incluso el propio `process` global no son accesibles fuera-de-la-caja. El módulo `process.env` sólo puede ser inyectado a través de la configuración de Webpack.
|
348
|
-
|
349
|
-
Si estás usando [`react-scripts`](https://www.npmjs.com/package/react-scripts), el cual se distribuye a través de [`create-react-app`](https://create-react-app.dev/), tiene dotenv incorporado pero con una singularidad. Escriba sus variables de entorno con `REACT_APP_`. Vea [este stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) para más detalles.
|
350
|
-
|
351
|
-
Si estás utilizando otros frameworks (por ejemplo, Next.js, Gatsby...), debes consultar su documentación para saber cómo injectar variables de entorno en el cliente.
|
352
|
-
|
353
|
-
### ¿Puedo personalizar/escribir plugins para dotenv?
|
354
|
-
|
355
|
-
Sí! `dotenv.config()` devuelve un objeto que representa el archivo `.env` analizado. Esto te da todo lo que necesitas para poder establecer valores en `process.env`. Por ejemplo:
|
356
|
-
|
357
|
-
```js
|
358
|
-
const dotenv = require('dotenv')
|
359
|
-
const variableExpansion = require('dotenv-expand')
|
360
|
-
const miEnv = dotenv.config()
|
361
|
-
variableExpansion(miEnv)
|
362
|
-
```
|
363
|
-
|
364
|
-
### Cómo uso dotnev con `import`?
|
365
|
-
|
366
|
-
Simplemente..
|
367
|
-
|
368
|
-
```javascript
|
369
|
-
// index.mjs (ESM)
|
370
|
-
import * as dotenv from 'dotenv' // vea https://github.com/motdotla/dotenv#como-uso-dotenv-con-import
|
371
|
-
dotenv.config()
|
372
|
-
import express from 'express'
|
373
|
-
```
|
374
|
-
|
375
|
-
Un poco de historia...
|
376
|
-
|
377
|
-
> Cuando se ejecuta un módulo que contiene una sentencia `import`, los módulos que importa serán cargados primero, y luego se ejecuta cada bloque del módulo en un recorrido en profundidad del gráfico de dependencias, evitando los ciclos al saltarse todo lo que ya se ha ejecutado.
|
378
|
-
>
|
379
|
-
> – [ES6 en Profundidad: Módulos](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
|
380
|
-
|
381
|
-
¿Qué significa esto en lenguaje sencillo? Significa que se podrías pensar que lo siguiente funcionaría pero no lo hará.
|
382
|
-
|
383
|
-
```js
|
384
|
-
// notificarError.mjs
|
385
|
-
import { Cliente } from 'mejor-servicio-para-notificar-error'
|
386
|
-
|
387
|
-
export default new Client(process.env.CLAVE_API)
|
388
|
-
|
389
|
-
// index.mjs
|
390
|
-
import dotenv from 'dotenv'
|
391
|
-
dotenv.config()
|
392
|
-
|
393
|
-
import notificarError from './notificarError.mjs'
|
394
|
-
notificarError.report(new Error('ejemplo documentado'))
|
395
|
-
```
|
396
|
-
|
397
|
-
`process.env.CLAVE_API` será vacio.
|
398
|
-
|
399
|
-
En su lugar, el código anterior debe ser escrito como...
|
400
|
-
|
401
|
-
```js
|
402
|
-
// notificarError.mjs
|
403
|
-
import { Cliente } from 'mejor-servicio-para-notificar-errores'
|
404
|
-
|
405
|
-
export default new Client(process.env.CLAVE_API)
|
406
|
-
|
407
|
-
// index.mjs
|
408
|
-
import * as dotenv from 'dotenv'
|
409
|
-
dotenv.config()
|
410
|
-
|
411
|
-
import notificarError from './notificarError.mjs'
|
412
|
-
notificarError.report(new Error('ejemplo documentado'))
|
413
|
-
```
|
414
|
-
|
415
|
-
¿Esto tiene algo de sentido? Esto es poco poco intuitivo, pero es como funciona la importación de módulos en ES6. Aquí hay un ejemplo [ejemplo práctico de esta trampa](https://github.com/dotenv-org/examples/tree/master/dotenv-es6-import-pitfall).
|
416
|
-
|
417
|
-
Existen dos arternativas a este planteamiento:
|
418
|
-
|
419
|
-
1. Precarga dotenv: `node --require dotenv/config index.js` (_Nota: no es necesario usar `import` dotenv con este método_)
|
420
|
-
2. Cree un archivo separado que ejecutará `config` primero como se describe en [este comentario #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
|
421
|
-
|
422
|
-
### ¿Qué pasa con la expansión de variable?
|
423
|
-
|
424
|
-
Prueba [dotenv-expand](https://github.com/motdotla/dotenv-expand)
|
425
|
-
|
426
|
-
### ¿Qué pasa con la sincronización y la seguridad de los archivos .env?
|
427
|
-
|
428
|
-
Vea [dotenv-vault](https://github.com/dotenv-org/dotenv-vault)
|
429
|
-
|
430
|
-
## Guía de contribución
|
431
|
-
|
432
|
-
Vea [CONTRIBUTING.md](CONTRIBUTING.md)
|
433
|
-
|
434
|
-
## REGISTRO DE CAMBIOS
|
435
|
-
|
436
|
-
Vea [CHANGELOG.md](CHANGELOG.md)
|
437
|
-
|
438
|
-
## ¿Quiénes utilizan dotenv?
|
439
|
-
|
440
|
-
[Estos módulos npm dependen de él.](https://www.npmjs.com/browse/depended/dotenv)
|
441
|
-
|
442
|
-
Los proyectos que lo amplían suelen utilizar la [palabra clave "dotenv" en npm](https://www.npmjs.com/search?q=keywords:dotenv).
|