Read environmet variable from cordova hook

252 views Asked by At

I have an ionic project which hosts the environment variables under src/environments/ which has classic environment.ts and environment.prod.ts files.

In the root folder, I have my cordova hook under scripts/afterBuild.js

In my config.xml i call my hook like this:

<hook src="/scripts/afterBuild.js" type="after_build" />

QUESTION

How can I read the production variable from the environment.ts file to my afterBuild.js script?

environment.ts:

export const environment = {
  ...
  production: false
};

WHAT I HAVE TRY

I can only read the file as text but cannot find a way to parse it.

afterBuild.js

const fs = require('fs');
var path = require('path');

module.exports = function (ctx) {
  var envFile = 'src/environments/environment.ts';
  var configFileFull = path.join(ctx.opts.projectRoot, envFile);
  var configData = fs.readFileSync(configFileFull, 'utf8');
  console.log(configData)
};
1

There are 1 answers

0
Iraklis Bekiaris On

I managed to find a solution. It goes like this:

When I run a cordova commande like for example:

cordova build

I can run it like this

cordova build --prod --something --somethingElse false

then, the ctx variable from

module.exports = function (ctx) {
  ...
};

has the

...
opts:{
   ...,
   options: { production: true, something: true, somethingElse: false }
},
...

It is not the best solution for me but it could work. Any other solution welcome :)