0

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 ?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • `process` is a node.js global. using ES6 or anything other syntax should not change it. How are you running it? – Slava Knyazev Feb 03 '23 at 20:26
  • Might be helpful but when I was starting to use `dotenv` I ran into an issue so I asked this question: "[Why are my custom process.env not working within dotenv?](https://stackoverflow.com/questions/57213162/why-are-my-custom-process-env-not-working-within-dotenv)" – DᴀʀᴛʜVᴀᴅᴇʀ Feb 03 '23 at 20:27

3 Answers3

0

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.

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
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'))
Hicham Mounadi
  • 429
  • 6
  • 8
-1

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.

Richard
  • 2,226
  • 2
  • 19
  • 35
-1

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

D. Melo
  • 2,139
  • 2
  • 14
  • 19