用于根据环境变量更新 config.json 的预构建脚本

MHO*_*OOS 6 typescript angular-cli angular angular9 angular-cli-v9

我有一个 angular 9 应用程序,我在其中从资产文件夹中读取了 api url:

@Injectable()
export class ConfigService {

  private configUrl = '../../../assets/config/config.json';

  constructor(private loggerService: LoggerService) { }

  public async loadConfig(): Promise<any> {
    try {
      const response = await fetch(this.configUrl);

      if (!response.ok) {
        throw new Error(response.statusText);
      }

      return await response.json();
    } catch (err) {
      this.loggerService.error(`ConfigService 'loadConfig' threw an error on calling ${this.configUrl} : ${err.tostring()}`);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用于读取配置文件的方法在构建后配置角度生产文件中描述。

environment.ts

export const environment = {
  production: false,
  apiUrl: "https://localhost/api/",
};
Run Code Online (Sandbox Code Playgroud)

environment.prod.ts

export const environment = {
  production: true,
  apiUrl: "https://server/api/",
};
Run Code Online (Sandbox Code Playgroud)

config.json

{
  "apiUrl": "http://someTestServer/api/"
}
Run Code Online (Sandbox Code Playgroud)

要复制到的不完整脚本apiUrlconfig.json

var fs = require("fs");
fs.readFile(`./src/environments/environment.${process.env.CONFIG}.ts`, 'utf8', function (err, data) {

  fs.writeFile('./src/assets/config/config.json', data, function (err) {
    if (err) throw err;
    console.log('complete');
  });
});
Run Code Online (Sandbox Code Playgroud)

我的 package.json 脚本部分如下所示:

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build-test": "CONFIG=test node update-config.js && npm run build",
    "build-prod": "CONFIG=prod node update-config.js && npm run predeploy",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "predeploy": "ng build --prod",
    "deploy": "node ftpdeploy.js"
  }
Run Code Online (Sandbox Code Playgroud)

考虑到上述情况:如何config.json在构建之前根据不同的环境变量自动填充文件的内容,这样我就不需要手动将 json 文件复制并粘贴到\dist文件夹中?

更新 1:现在我可以将我的 environment.xxx.ts 的内容复制到 config.json 文件中。还有一个问题:当我从 environment.xxx.ts 复制内容时,它会将 environment.xxx.ts 的全部内容复制到 config.json(它还复制我的 environment.xxx.ts 的导入部分)但是预期的结果是将environment( export const environment)读入一个对象并根据源environment对象更新 config.json 。我怎样才能做到这一点?

Dan*_*cci 6

将预构建脚本更改为:

const fs = require("fs");
fs.readFile(`/src/environments/${process.env.CONFIG}.ts`, (err, content) => {
  fs.writeFile("/src/assets/config/config.json", JSON.stringify(versionObject), () => { });
});
Run Code Online (Sandbox Code Playgroud)

然后从命令行(我假设npm run build是要构建的命令,否则使用您的构建命令更改它):

$ CONFIG=environment npm run build
Run Code Online (Sandbox Code Playgroud)

应该可以解决你的问题。

编辑:

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  // add more lines as you need like this, one for each build environment
  "build-test": "CONFIG=test node update-config.js && npm run build",
  "build-prod": "CONFIG=prod node update-config.js && npm run predeply",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e",
  "predeploy": "ng build --prod",
  "deploy": "node ftpdeploy.js"
},
Run Code Online (Sandbox Code Playgroud)

\在您的问题中注意到了一个,可能您在 Windows 下运行,请确保使用bash:添加一个.npmrc仅使用以下行调用的文件script-shell=bash

编辑:如果你想用 读取环境文件fetch并用 解析它await response.json(),文件应该是一个 json 文件,而不是一个 ts 文件:

{
  production: true,
  apiUrl: "https://server/api/",
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。