I'm trying to read environmental variables in ES6.
import dotenv from "dotenv";
dotenv.config()
I did the following however when I attempt to use
process.env.example
Like I've always done in common JS I get an error message stating that process is not defined. Can someone help me ?
CodePudding user response:
in it's written in their docs
import * as dotenv from 'dotenv'
dotenv.config()
Here is an explanation ; you can read more here => https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-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.
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
import dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))
process.env.API_KEY will be blank.
Instead the above code should be written as..
// errorReporter.mjs
import { Client } from 'best-error-reporting-service'
export default new Client(process.env.API_KEY)
// index.mjs
import * as dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))
CodePudding user response:
Uncaught ReferenceError: process is not defined
is the message you get when running process.env.example
in the browser console. You will only be able to access this environment variable on the server side, and not the client side.
CodePudding user response:
Maybe do
import * as dotenv from 'dotenv'
As indicated by that library docs in case you are using ES6 instead of the old require()
method.
See also: https://www.npmjs.com/package/dotenv