In Angular, the the de facto way to load env vars into the app is using environment.ts
which is part of the cli.
In NativeScript, it seems like that doesn't work with the NativeScript cli.
What's the best way to do so?
If you're using webpack with NativeScript, you can pass environment variables into webpack which you can then access from your code. When you install NativeScript webpack for the first time, it will generate a webpack.config.js in the same folder that your package.json is in. Open webpack.config.js in a code editor and search for new webpack.DefinePlugin
and modify it like so:
new webpack.DefinePlugin({
"global.TNS_WEBPACK": "true",
'process.env': {
'envtype': JSON.stringify(env && env.envtype ? env.envtype : ""),
'gmapsKey': JSON.stringify(env && env.gmapsKey ? env.gmapsKey : ""),
'stripeKey': JSON.stringify(env && env.stripeKey ? env.stripeKey : ""),
// etc, these are just examples
}
}),
Then, inject your environment variables during build:
// for example
tns run android --bundle --env.envtype="dev" --env.gmapsKey="KEY_HERE" --env.stripeKey="KEY_HERE"
Then, you can access your environment variables in-code like so:
You can create an Angular service and access your injected variables in any component you want.
import { Injectable } from '@angular/core';
declare var process: any;
@Injectable()
export class EnvironmentManagerService {
private getEnvironmentVars(key: string): string {
if (typeof process !== 'undefined' && process && process.env) {
return process.env[key];
} else {
return "";
}
}
public getGoogleMapsKey(): string {
return this.getEnvironmentVars("gmapsKey");
}
public getStripePublishableKey(): string {
return this.getEnvironmentVars("stripeKey");
}
public isDev(): boolean {
return this.getEnvironmentVars("envtype") === "dev";
}
}
Create a new file in your project under your app folder. You can call the file anything you want. Add the following:
declare var process: any;
export function getEnvironmentVars(key: string): string {
if (typeof process !== 'undefined' && process && process.env) {
return process.env[key];
} else {
return "";
}
}
You can import that file from anywhere with import * as env from '<file path here>'
and call env.getEnvironmentVars(...)
, e.g. env.getEnvironmentVars("gmapsKey")
.
There might also be ways to simulate the same environment.ts and environment.prod.ts approach by conditionally modifying the files that webpack includes, but I didn't explore that approach as the above was sufficient for my purposes.
If you aren't using webpack, you can use the custom hooks approach, although I've never used it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With