如何为我的角度应用程序在heroku中使用环境变量?

时间:2019-08-27 21:17:23

标签: angular heroku

我试图为我的heroku中的角度应用设置环境变量(或Heroku世界中的Config Vars),例如production = true。但是,我不知道如何设置postinstallbuild脚本来使用它们。将其放在我的packahge.json文件中:

"postinstall": "ng build --aot --configuration=${ENV}"

只是导致Heroku运行以下命令:

> ng build --aot --configuration=${ENV}

如果我无法更改构建配置,则无法利用angular的文件替换来设置诸如Firebase api键之类的东西。

我发现this article似乎表明我可以访问package.json文件中的配置变量,但是它不起作用。

我还尝试在我的environment.ts文件中仅使用process.env.FIREBASE_API_KEY并完全绕过文件替换,并且在该应用程序成功在heroku中构建的同时,我在控制台中看到了

Uncaught ReferenceError: process is not defined

我不确定处理此问题的最佳方法是什么。谢谢!

3 个答案:

答案 0 :(得分:0)

您可以像下面的article那样使用Heroku信息中心设置环境变量

像这样设置环境变量可让您动态控制环境变量

因此在Node.js中,使用process.env.something访问环境变量

答案 1 :(得分:0)

我能够通过以下方法克服这一点:

  1. 将配置变量ENV设置为productionstaging

  2. 创建post-install.js文件:

const { exec } = require('child_process');

let command;

if (process.env.ENV === 'production') {
    command = exec('ng build --aot --configuration=production');
} else if (process.env.ENV === 'staging') {
    command = exec('ng build --aot --configuration=staging');
}

if (command != undefined) {
    command.stdout.on('data', (data) => {
        console.log(data);
    });

    command.stderr.on('data', (data) => {
        console.error(data);
    });

    command.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
    });
} else {
    console.error('process.env.ENV: ' + process.env.ENV);
}
  1. 然后我修改了package.json的{​​{1}}脚本以运行该文件
postinstall

因此,当Heroku运行后安装脚本时,它将构建适当的版本(并替换正确的环境文件)。

答案 2 :(得分:0)

我尝试了多种方法来正确构建Heroku方面。 然后我决定这对我来说不是一个好主意。

现在,我在本地构建,然后推送到Heroku(或git)。

要在Heroku方面使用ENV var,我使用PHP 获取env并传递给应用程序索引。

在此示例中,我得到api_url:

在INDEX.HTML中

<script>

    let apiFromEnv = '<?php echo getenv("API_URL")?>'
    if (apiFromEnv.indexOf('.com') > 0) {
        document.apiURL = apiFromEnv
    } else {
        document.apiURL = null
    }

</script>

在打字稿中使用时:

let apiURL = environment.API_URL;
if (document['apiURL']) {
  apiURL = document['apiURL'];
}

此行之后,我举一个示例将您的节点应用程序切换为php

将您的应用程序构建包切换为php,请使用 composer.json

在heroku安装之后,您必须将index.html名称更改为index.php;这是 composer.json 文件(将其放置为Procfile附近项目的根目录),它包含用于更改Heroku构造的php。

{
  "require": {
    "php": "^7.1.3"
  },
  "scripts": {
    "post-install-cmd": [
      "mv dist/index.html dist/index.php"
    ]
  }
}

我使用 .htaccess 重定向服务器的规则和目录索引:

DirectoryIndex index.php
<IfModule mod_rewrite.c>
RewriteEngine On

# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.php
RewriteRule ^ index.php

</IfModule>

最后一件事,不要忘记将.htaccess添加到angular.json资产复制规则:

"architect": {
    "build": {
      .....,
      "options": {
        ....
        "assets": [
          .....,
          "src/.htaccess"
        ],
......
相关问题