What is the best ways to set up different environment variables for NativeScript with Angular?
Asked Answered
R

2

6

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?

Ransell answered 20/7, 2018 at 20:52 Comment(0)
A
10

Updated 8/25/2018

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:

With Angular

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";
    }
}

Without Angular

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.

Arak answered 23/7, 2018 at 1:49 Comment(4)
Thanks, I'll try this and report back. My team said Webpack was a pain to setup / learn before. It seems from your response it's not that much effort.Ransell
It sure can be depending on the codebase that you're working on -- sometimes it's easy, other times you'll be googling why your code doesn't compile when bundling is enabled.Arak
Is it possible to get these variable values from build.xconfig instead of CLI parameters?Marrufo
I don't see why not. Before you define the plugin, you can read your xconfig file -- it's just Nodejs. There's probably an npm module somewhere out there for it too.Arak
R
0

The following by default is set in the webpack.config.js file:

new webpack.DefinePlugin({
    'global.TNS_WEBPACK': 'true',
    TNS_ENV: JSON.stringify(mode),
    process: 'global.process'
}),

The mode variable is taken from the following code in the webpack.config.js file:

const mode = production ? 'production' : 'development';

To set the production variable in webpack.config.js you must set the --release flag when building/running. https://docs.nativescript.org/tooling/docs-cli/project/testing/run.html states:

--release - If set, produces a release build by running webpack in production mode and native build in release mode. Otherwise, produces a debug build.

This means to test "production mode" locally without building a release .apk file, you must do what arao6 said.

Reiner answered 24/10, 2020 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.