Loads environment variables from a .env file into process.env

Hi everyone,

I try to load variables from the .env file into process.env in order not to make my API keys visible.
In the root of my project I created a file .env. This file includes my variables



Then I created a setenv.ts file. This file should set the environment variable.

const { writeFile } = require('fs');
const { argv } = require('yargs');

// read environment variables from .env file

// read the command line arguments passed with yargs
const environment = argv.environment;
const isProduction = environment === 'prod';

const targetPath = isProduction
   ? `./src/environments/environment.prod.ts`
   : `./src/environments/environment.ts`;

// we have access to our environment variables
// in the process.env object thanks to dotenv
const environmentFileContent = `
export const environment = {
   production: ${isProduction},
   test: "${process.env['API_KEY']}",

// write the content to the respective file
writeFile(targetPath, environmentFileContent, (err:any) => {
   if (err) {

   console.log(`Wrote variables to ${targetPath}`);

Finally, I want to execute setenv.ts before the build. During my research I found approaches to change the “scripts” section in package.json:

 "scripts": {
    "ng": "ng",
    "start": "ts-node setenv.ts && ng serve",
    "build": "ts-node setenv.ts && ng build",
    "watch": "ts-node setenv.ts && ng build --watch --configuration development",
    "test": "ng test",
    "lint": "ng lint"

However, when I modify the “script” section or even delete it, my ionic CLI commands (ionic build or ionic serve) still work the same way.

Can someone help we with my issue please. I have tried a lot of different approaches, but nothing works for me :frowning:

Here is some information about my environment. When typing ionic info, I got:


   Ionic CLI                     : 6.20.4 (/Users/username/.nvm/versions/node/v12.18.1/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 6.7.5
   @angular-devkit/build-angular : 15.0.4
   @angular-devkit/schematics    : 13.3.10
   @angular/cli                  : 15.0.4
   @ionic/angular-toolkit        : 6.1.0


   cordova-res (update available: 0.15.4) : 0.15.3
   native-run (update available: 2.0.0)   : 1.7.1


   NodeJS : v18.12.1 (/Users/username/.nvm/versions/node/v18.12.1/bin/node)
   npm    : 9.2.0
   OS     : macOS

I thank you in advance