【问题标题】:How to run a different build command for staging environment when publishing a react amplify application发布反应放大应用程序时如何为登台环境运行不同的构建命令
【发布时间】:2022-03-04 20:19:08
【问题描述】:

到目前为止,我有一个具有两个环境的放大反应应用程序:prod 和 staging。

然后我的.env.staging.env.production 文件具有不同的 API URL 值。

因此,在我的 package.json 中,我为部署准备了以下脚本:

"build":           "react-scripts build",
"build:staging":   "env-cmd -f .env.staging react-scripts build",

现在问题来了,因为我不知道如何使 amplify publish 命令根据环境运行其中一个或另一个。

无论我选择哪个amplify env checkout,'publish'命令使用的配置都共享在'project-config.json'中,如下所示:

{
    "projectName": "whatever",
    "version": "3.0",
    "frontend": "javascript",
    "javascript": {
        "framework": "react",
        "config": {
            "SourceDir": "src",
            "DistributionDir": "build",
            "BuildCommand": "npm.cmd run-script build",
            "StartCommand": "npm.cmd run-script start"
        }
    },
    "providers": [
        "awscloudformation"
    ]
}

有什么方法可以实现我想要的吗?

提前感谢您的帮助。

【问题讨论】:

    标签: reactjs aws-amplify aws-amplify-cli


    【解决方案1】:

    我知道这个问题是大约 1 年前提出的,但今天早上我遇到了同样的问题,并想提供我的解决方案。

    目前(截至 22 年 4 月 3 日)there is still no official solution to the problem,因此,您将需要编辑构建脚本以根据环境动态构建内容。

    我们目前实现这一点的方式是在我们的根目录中创建一个构建 JS 脚本(名为 build-env.script.js),其中包含以下代码:

    #! /usr/bin/env node
    (function() {
      // bring in child_process to use spawn command
      const cp = require('child_process');
      // bring in the amplify local-env-info.json to see current environment
      const buildInfo = require('./amplify/.config/local-env-info.json');
      // spawn the build command based on the env name:
      // npm run build-production on prod or npm run build-staging on staging
      const cmd = cp.spawn(`npm run build-${buildInfo.envName}`, { shell: true });
      // echo output of the commands to the console
      cmd.on('spawn', () => console.log('Running build command for:', buildInfo.envName));
      cmd.stdout.on('data', (d) => console.log(d.toString()));
      cmd.stderr.on('data', (d) => console.log(d.toString()));
      cmd.on('exit', () => console.log('Build Completed'));
    })();
    

    作为旁注,有问题的 JSON 文件是由 amplify 创建的,因此在查找当前环境名称时可以确定为事实来源,例如,我的文件如下所示:

    {
      "projectPath": "path/to/project/frontent",
      "defaultEditor": "vscode",
      "envName": "production"
    }
    

    虽然我的 package.json 看起来像这样:

    {
      ...
      "scripts": {
        ...
        "build": "node ./build-env.script.js",
        "build-staging": "ng build --configuration staging",
        "build-production": "ng build --configuration production"
      }
    }
    

    但是,您需要相应地修改环境名称和脚本(因为我们的项目是 Angular 项目。

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 2021-11-03
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2013-09-25
      • 1970-01-01
      相关资源
      最近更新 更多