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

标签 angular typescript angular-cli angular9 angular-cli-v9

我有一个 angular 9 应用程序,我在其中从 Assets 文件夹中读取了 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()}`);
    }
  }
}
用于读取配置文件的方法在 Configuring angular production files after build 中描述。environment.ts
export const environment = {
  production: false,
  apiUrl: "https://localhost/api/",
};
environment.prod.ts
export const environment = {
  production: true,
  apiUrl: "https://server/api/",
};
config.json
{
  "apiUrl": "http://someTestServer/api/"
}
不完整的 脚本将 apiUrl 复制到 config.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');
  });
});
我的 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"
  }
考虑到上述情况:如何在构建之前根据不同的环境变量自动填充 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。我怎样才能做到这一点?

最佳答案

将预构建脚本更改为:

const fs = require("fs");
fs.readFile(`/src/environments/${process.env.CONFIG}.ts`, (err, content) => {
  fs.writeFile("/src/assets/config/config.json", JSON.stringify(versionObject), () => { });
});
然后从命令行(我假设 npm run build 是要构建的命令,否则使用您的构建命令更改它):
$ CONFIG=environment npm run build
应该可以解决你的问题。
编辑:
"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"
},
我注意到一个 \在您的问题中,可能您在 Windows 下运行,请确保使用 bash : 添加一个名为 .npmrc 的文件只有以下行 script-shell=bash 编辑:如果你想用 fetch 读取环境文件并用 await response.json() 解析它,该文件应该是一个json文件,而不是一个ts文件:
{
  production: true,
  apiUrl: "https://server/api/",
}
希望这可以帮助。

关于angular - 用于根据环境变量更新 config.json 的预构建脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62398794/

相关文章:

javascript - 在 angular2 路由应用程序中单击后退按钮时会发生什么?

Angular 2 : clear textarea from component class

javascript - Angular 5 - 每次迭代缩进

reactjs - useRef 不起作用 [TypeError : null is not an object (evaluating 'filed2.current.focus' )]

Angular 5 HttpInterceptor this.interceptor.intercept 不是一个函数

javascript - Node typescript 项目中的 Jest 覆盖总是返回空

typescript - 检查变量是否是 typescript 联合中的特定接口(interface)类型

angular - 从 6.1 更新后,@Input() 在 Angular 9 上具有空值

javascript - Angular 网站部署问题

angular - 如何在独立的 Angular 2 组件中包含字体