【问题标题】:Passing environment-dependent variables in nativescript & angular2在 nativescript 和 angular2 中传递与环境相关的变量
【发布时间】:2023-03-05 07:18:01
【问题描述】:

我正在使用 NativeScript (2.3.0) 和 Angular2 (2.0.0) 构建一个移动应用程序

我正在努力如何根据环境(开发/测试/产品)加载环境变量的方式将环境变量排除在我们的源代码之外。

理想情况下,我希望拥有保存它们的专用文件(.env.dev .env.test .env.prod),但我愿意接受任何可行的解决方案。

无论是 Native Script 文档还是谷歌搜索,我都找不到任何帮助。

【问题讨论】:

    标签: nativescript angular2-nativescript


    【解决方案1】:

    经过一番研究,我得到了一个解决方案,并将其发布以供将来参考:

    受此文档启发:https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-pass-environment-variables%3F

    这都是关于在全局命名空间中发布变量并使用 Webpack 通过new webpack.DefinePlugin (https://webpack.github.io/docs/list-of-plugins.html#dependency-injection) 覆盖它们。

    分步指南:

    • 将 Webpack 安装为 NS 模块:tns install webpack(更多信息https://docs.nativescript.org/tooling/bundling-with-webpack
    • 将 Webpack 安装为 node_module:npm install --save-dev webpack(我知道这似乎是多余的,但这是我发现可以从 webpack.config.js 访问 webpack 对象的唯一方法)

    • 在webpack.config.js中修改如下:(其他不相关的配置已省略)

      var bundler = require("nativescript-dev-webpack");
      var webpack = require("webpack");
      
      module.exports = bundler.getConfig({
      
        plugins: [
          new webpack.DefinePlugin({
            'ENV': JSON.stringify('dev'),
            'API_URL': JSON.stringify('my_api_url'),
            'HMR': 'whatever',
          })
        ]
      });
      

    /app 文件夹中创建以下文件,旨在用全局变量填充全局命名空间(据说它们将被 Webpack 覆盖)

    global-environment.ts

    // Extra variables that live on Global that will be replaced by webpack DefinePlugin
    declare var ENV: string;
    declare var HMR: boolean;
    declare var API_URL: string;
    
    interface GlobalEnvironment {
        ENV;
        HMR;
        API_URL;
    }
    

    完成!

    也许您对此有更好的方法/改进。我很高兴听到他们的声音。

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 2018-09-18
      • 2016-09-05
      • 1970-01-01
      相关资源
      最近更新 更多