1

到目前为止,我有一个具有两个环境的放大反应应用程序: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我选择哪个,“发布”命令中使用的配置都在“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"
    ]
}

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

提前感谢您的帮助。

4

1 回答 1

0

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

目前(截至 22 年 4 月 3 日)仍然没有官方解决该问题的方法,因此,您需要编辑构建脚本以根据环境动态构建内容。

我们目前实现这一点的方式是在我们的根目录(名为 build-env.script.js)中创建一个构建 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 项目。

于 2022-03-04T12:19:08.697 回答