Environment variables in parcel nested modules

Viewed 187

I'm trying to use environment variables in "nested" dependencies of a project bundled with Parcel, using .env files, but I'm getting undefined instead of the desired value.

According to the docs, NODE_ENV is automatically set to "production" when building, else it's set to "development", so it will load .env.local either .env.production depending on that value.

Consider my file structure:

./
├── .env.local
├── .env.production
├── src
│   ├── index.html
│   ├── scripts
│   │   ├── main.js
│   │   └── APIService.js
└── package.json

My script for launching the app in package.json is this:

   "scripts": {
      "start": "parcel src/index.html"
   }

… and the src/index.html file loads the main.js file with a simple tag:

<!DOCTYPE html>
<!-- ... -->

<script src="main.js" defer></script>

If I try to log an environment variable set in .env.local in main.js, it will work perfectly because it is the JS entry point, but if I try to get the same exact variable into an imported module like APIService.js, I get undefined:

// main.js

import APIService from "./APIService";

console.log(process.env.API_ENDPOINT); // ✅ http://localhost:5001/functions/app
// APIService.js

console.log(process.env.API_ENDPOINT); // ❌ undefined

Am I missing something?

How to get access to the environment variables inside imported files?

PS: I've already tried to use the dotenv package in addition, but without success.

0 Answers
Related