【问题标题】:Replace a variable inside a typescript file from windows batch script从 Windows 批处理脚本替换打字稿文件中的变量
【发布时间】:2019-02-25 09:29:02
【问题描述】:

我想修改一个 typescript 文件,该文件在 angular 6 项目中保存环境信息。变量值必须仅在构建时更改,该构建通过批处理文件启动。

环境文件如下所示:(其中 build 是要更改/替换的变量)

export const environment = {
  host: 'http://localhost:8080',
  build: "1.0.0.0"
};

我发现很难通过批处理文件来做同样的事情。不同环境(local/qa/dev/prod)的环境文件不同,构建由构建工程师发起。 当前构建过程调用 webpack 命令,并压缩输出。

有没有办法从每个构建中动态替换“构建”值?

编辑: 从https://www.bilyachat.com/blog/angular-2-build-version 中找到一种方法。很快就会更新为答案。

【问题讨论】:

  • 可能你需要等待。这仍然从角度侧打开github.com/angular/angular-cli/issues/4318
  • 在 angular.json 中有一个 fileReplacements "tag"
  • @Eliseo 不幸的是我没有使用 angular.cli,而是 webpack

标签: angular windows batch-file webpack build


【解决方案1】:

我自己解决了。 我的解决方案是:

  1. 在配置文件中添加了一个变量,适用于每个环境
  2. 添加了“replace-in-file”节点库,用于替换特定内容(变量- '%VERSION%'),在特定的配置文件中,传递的值 在package.json 中调用ng-build-qa: node ./replace.build.js 命令时
  3. 'replace.build.js文件的内容是:
var replace = require('replace-in-file');
var buildVersion = process.argv[2];
const options = {
    files: 'environments/environment.qa.ts',
    from: "%VERSION%",
    to: ""+ buildVersion + "",
    allowEmptyPaths: false,
};

try {
    let changedFiles = replace.sync(options);
    if (changedFiles == 0) {
        throw "Please make sure that file '" + options.files + "' has \"version: ''\"";
    }
    console.log('Build version set: ' + buildVersion);
}
catch (error) {
    console.error('Error occurred:', error);
    throw error
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多