在Angular中为NativeScript设置不同的环境变量的最佳方法是什么?

Ka *_*Mok 3 nativescript angular2-nativescript

在Angular中,实际上是使用env var加载到应用程序中的,environment.ts这是cli的一部分。

在NativeScript中,这似乎不适用于NativeScript cli。

最好的方法是什么?

ara*_*ao6 6

更新于2018年8月25日

如果将webpack与NativeScript 一起使用,则可以将环境变量传递到webpack中,然后可以从代码中进行访问。首次安装NativeScript webpack时,它将在package.json所在的同一文件夹中生成一个webpack.config.js。在代码编辑器中打开webpack.config.js,如下所示进行搜索new webpack.DefinePlugin和修改:

        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
            }
        }),
Run Code Online (Sandbox Code Playgroud)

然后,在构建过程中注入环境变量:

// for example
tns run android --bundle --env.envtype="dev" --env.gmapsKey="KEY_HERE" --env.stripeKey="KEY_HERE"
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样通过代码访问环境变量:

带角

您可以创建Angular服务,并在所需的任何组件中访问注入的变量。

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

无角度

在您的项目的app文件夹下创建一个新文件。您可以根据需要调用该文件。添加以下内容:

declare var process: any;

export function getEnvironmentVars(key: string): string {
    if (typeof process !== 'undefined' && process && process.env) {
        return process.env[key];
    } else {
        return "";
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以从任何地方导入该文件,import * as env from '<file path here>'然后调用env.getEnvironmentVars(...),例如env.getEnvironmentVars("gmapsKey")


可能还有一些方法可以通过有条件地修改webpack包含的文件来模拟相同的environment.ts和environment.prod.ts方法,但是由于上述内容足以满足我的目的,因此我没有探索这种方法。

如果您不使用webpack,则可以使用自定义钩子方法,尽管我从未使用过。