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

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

在 Angular 中,将环境变量加载到应用程序中的实际方法是使用 environment.ts,它是 cli 的一部分。

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

最好的方法是什么?

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
            }
        }),

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

// for example
tns run android --bundle --env.envtype="dev" --env.gmapsKey="KEY_HERE" --env.stripeKey="KEY_HERE"

然后,您可以像这样在代码中访问您的环境变量:

与Angular

您可以创建一个 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";
    }
}

没有Angular

在您的应用程序文件夹下的项目中创建一个新文件。您可以随意调用该文件。添加以下内容:

declare var process: any;

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

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


可能还有一些方法可以通过有条件地修改 webpack 包含的文件来模拟相同的 environment.ts 和 environment.prod.ts 方法,但我没有探索这种方法,因为上面的方法对我来说已经足够了目的。

如果你不使用 webpack,你可以使用 custom hooks 方法,虽然我从未使用过它。

webpack.config.js 文件中的默认设置如下:

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

mode变量取自webpack.config.js文件中的以下代码:

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

要在 webpack.config.js 中设置 production 变量,您必须在 building/running 中设置 --release 标志。 https://docs.nativescript.org/tooling/docs-cli/project/testing/run.html 状态:

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

这意味着要在本地测试“生产模式”而不构建发布 .apk 文件,您必须按照 arao6 所说的进行操作。