【问题标题】:Angular CLI to modify a TS file before building?Angular CLI 在构建之前修改 TS 文件?
【发布时间】:2018-07-13 12:22:55
【问题描述】:

我正在使用 Angular 6 和 Angular CLI 来构建 AOT。 SPA 有一个关于对话框来告诉当前的前端版本,基本上是 YYMMDD:mm。我将版本存储在environments/environment.ts中:

export const AppConfigConstants: AppConfigConstantsType = {

    version: '180709.13',

};

当前在运行之前

ng build --configuration=production

我必须手动修改版本。如果能自动更新版本号就更好了。

Angular CLI 有没有很好的修改 TS 文件的功能?还是您有其他解决方案?

【问题讨论】:

  • 创建一个执行替换的 npm 脚本并在之后调用 CLl 构建

标签: angular typescript angular-cli angular-cli-v6


【解决方案1】:

您可以向npm build 添加一个脚本,在运行ng build 之前增加您的版本号:

版本号可以存储在您可以在应用程序中读取的 JSON 文件中:

src/version.json

{
    "v": 0
}

increment-version.js

// read version.json from file system, increment the version by 1

const fs = require("fs");
fs.readFile("src/version.json", (err, content) => {
    const versionObject = JSON.parse(content.toString());
    versionObject.v ++;
    fs.writeFile("src/version.json", JSON.stringify(versionObject), () => {});
});

package.json

"scripts": {
    ...
    "build": "node increment-version.js && ng build"
}

angular.json

"assets": [
    ...
    "src/version.json"
]

typings.d.ts

....
declare module "*.json" {
    const value: any;
    export default value;
}

about-dialog.ts

import * as version from '../version.json';
const versionNumber = version.v;

【讨论】:

  • 感谢您的启发。我已经提出了我的解决方案。
【解决方案2】:

我是一个批处理文件,一般调用ng build。

批处理文件是这样的:

cd %~dp0NGSource

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x

set today=%MyDate:~0,4%%MyDate:~4,2%%MyDate:~6,2%%time:~0,2%%time:~3,2%

@echo const BUILD_TIME={buildTime: %today%} > src\conf\buildTime.js

ng build --configuration=production

而buildTime.js包含在angular.json的scripts节点中,所以捆绑在scripts.xxxxx.js中。 MY TS 代码通过这样的声明访问这个文件:

declare const BUILD_TIME: {
    buildTime?: string;
}

interface AppConfigConstantsType {
    version: string;
    buildTime?: string;
}

export const AppConfigConstants: AppConfigConstantsType = {
    version: '2.3',
    ...(typeof BUILD_TIME === 'undefined' ? { buildTime: 'Unknown' } : BUILD_TIME),
};

最后,我决定将版本号和内部版本号分开。如果你想将它们组合成一个字符串,你应该不难调整上面的代码。

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2019-04-21
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多