Skip to content

Instantly share code, notes, and snippets.

@lynsei
Last active February 17, 2022 18:10
Show Gist options
  • Save lynsei/b0996fda186ec8591ca5bc0ac73adc5e to your computer and use it in GitHub Desktop.
Save lynsei/b0996fda186ec8591ca5bc0ac73adc5e to your computer and use it in GitHub Desktop.
[#dotenv usage] with #import instead of require (as a #Node Module rather than a require of CommonJS package)
API_KEY=api-key-123456789
class Client {
constructor(apiKey) {
this.apiKey = apiKey
}
report(err) {
console.log(this.apiKey, err)
}
}
export default new Client(process.env.API_KEY)

follow these examples:

gh repo clone dotenv-org/examples
import dotenv from 'dotenv'
dotenv.config() // this will NOT load process.env before errorReporter is loaded.
// ES6 modules are not intuitive like that. see valid.mjs for proper configuration
import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))

USAGE

An example of an ES6 import pitfall. See invalid.mjs and then valid.mjs.

Note how invalid.mjs does not correctly log the API_KEY environment variable.

See Below:

$ \
npm install &&\
node invalid.mjs &&\ 
node valid.mjs
import 'dotenv/config'
import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment