Vil*_*kas 24 angular-cli angular
我需要在angular2应用程序的页面上显示git revision.该项目基于angular-cli.
如何扩展构建,以便将git修订版放入environment.ts应用程序可访问的其他位置?
Vil*_*kas 42
正如@Yuri所说,我能够通过使用npm脚本来解决这个问题.
定义git.version.ts在angular-cli项目的根目录中:
import fs = require('fs');
import { Observable } from 'rxjs';
let exec = require('child_process').exec;
const revision = new Observable<string>(s => {
exec('git rev-parse --short HEAD',
function (error: Error, stdout: Buffer, stderr: Buffer) {
if (error !== null) {
console.log('git error: ' + error + stderr);
}
s.next(stdout.toString().trim());
s.complete();
});
});
const branch = new Observable<string>(s => {
exec('git rev-parse --abbrev-ref HEAD',
function (error: Error, stdout: Buffer, stderr: Buffer) {
if (error !== null) {
console.log('git error: ' + error + stderr);
}
s.next(stdout.toString().trim());
s.complete();
});
});
Observable
.combineLatest(revision, branch)
.subscribe(([revision, branch]) => {
console.log(`version: '${process.env.npm_package_version}', revision: '${revision}', branch: '${branch}'`);
const content = '// this file is automatically generated by git.version.ts script\n' +
`export const versions = {version: '${process.env.npm_package_version}', revision: '${revision}', branch: '${branch}'};`;
fs.writeFileSync(
'src/environments/versions.ts',
content,
{encoding: 'utf8'}
);
});
Run Code Online (Sandbox Code Playgroud)添加了预构建钩子package.json:
"scripts": {
"ng": "ng",
...
"start": "ng serve --proxy proxy-config.json",
"prebuild.prod": "ts-node git.version.ts",
"build.prod": "ng build -prod",
...
},
Run Code Online (Sandbox Code Playgroud)使用src/environments/versions.ts应用程序中生成的.
更新10/2018:这是更易读的脚本版本,rxjs-version-agnostic:
import { writeFileSync } from 'fs';
import { dedent } from 'tslint/lib/utils';
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function createVersionsFile(filename: string) {
const revision = (await exec('git rev-parse --short HEAD')).stdout.toString().trim();
const branch = (await exec('git rev-parse --abbrev-ref HEAD')).stdout.toString().trim();
console.log(`version: '${process.env.npm_package_version}', revision: '${revision}', branch: '${branch}'`);
const content = dedent`
// this file is automatically generated by git.version.ts script
export const versions = {
version: '${process.env.npm_package_version}',
revision: '${revision}',
branch: '${branch}'
};`;
writeFileSync(filename, content, {encoding: 'utf8'});
}
createVersionsFile('src/environments/versions.ts');
Run Code Online (Sandbox Code Playgroud)注意,当使用angular-cli v7.0.6时,我还必须在以下位置更改脚本调用package.json:
"scripts": {
...
"prebuild.prod": "ts-node -O '{\"module\": \"commonjs\"}' git.version.ts",
...
},
Run Code Online (Sandbox Code Playgroud)
Sau*_*47g 12
git-version.js到根。此代码将执行 git 命令并将输出写入git-version.json文件。const childProcess = require('child_process');
const { writeFileSync } = require('fs');
const longSHA = childProcess.execSync("git rev-parse HEAD").toString().trim();
const shortSHA = childProcess.execSync("git rev-parse --short HEAD").toString().trim();
const branch = childProcess.execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
const authorName = childProcess.execSync("git log -1 --pretty=format:'%an'").toString().trim();
const commitTime = childProcess.execSync("git log -1 --pretty=format:'%cd'").toString().trim();
const commitMsg = childProcess.execSync("git log -1 --pretty=%B").toString().trim();
const totalCommitCount = childProcess.execSync("git rev-list --count HEAD").toString().trim();
const versionInfo = {
shortSHA: shortSHA,
SHA : longSHA,
branch: branch,
lastCommitAuthor: authorName,
lastCommitTime: commitTime,
lastCommitMessage: commitMsg,
lastCommitNumber: totalCommitCount
}
const versionInfoJson = JSON.stringify(versionInfo, null, 2);
writeFileSync('/src/git-version.json', versionInfoJson);
Run Code Online (Sandbox Code Playgroud)
此代码将生成git-version.json文件:-
{
"shortSHA": "0e786d4",
"SHA": "0e786d4ad3778463f6f30c28f254cc85c24eb4b3",
"branch": "master",
"lastCommitAuthor": "'saurabh'",
"lastCommitTime": "'Thu Apr 9 12:59:16 2020 +0530'",
"lastCommitMessage": "Commit message",
"lastCommitNumber": "200"
}
Run Code Online (Sandbox Code Playgroud)
根据您的要求修改上面的代码。
运行:node git-version.js这将生成git-version.json进入src目录。
package.json"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"build.prod": "node git-version.js && ng build --prod"
}
Run Code Online (Sandbox Code Playgroud)
npm run build.prod欢迎提出代码改进建议:)
其他答案很有帮助,但我更喜欢一种更简单,直接的方法。这是我的。
运行npm install git-describe --save-dev。然后添加git-version.js到根目录:
// This script runs operations *synchronously* which is normally not the best
// approach, but it keeps things simple, readable, and for now is good enough.
const { gitDescribeSync } = require('git-describe');
const { writeFileSync } = require('fs');
const gitInfo = gitDescribeSync();
const versionInfoJson = JSON.stringify(gitInfo, null, 2);
writeFileSync('git-version.json', versionInfoJson);
Run Code Online (Sandbox Code Playgroud)
(可选)您可以添加/git-version.json到.gitignore文件中。
更新您package.json执行以下操作:
"scripts": {
"build": "node git-version.js && ng build"
}
Run Code Online (Sandbox Code Playgroud)
然后添加version-info.ts到项目的根目录:
export const versionInfo = (() => {
try {
// tslint:disable-next-line:no-var-requires
return require('../../git-version.json');
} catch {
// In dev the file might not exist:
return { tag: 'v0.0.0', hash: 'dev' };
}
})();
Run Code Online (Sandbox Code Playgroud)
而import在versionInfo您的app.component.ts或任何其他地方,你会想使用它。
我喜欢保持简单。可以添加到您的 index.html:
<script>window.version = '{git-hash}';</script>
Run Code Online (Sandbox Code Playgroud)
然后将postbuild脚本添加到您的package.json:
"postbuild": "sed -i '' \"s/{git\\-hash}/$(git rev-parse --short HEAD)/g\" dist/*/index.html"
Run Code Online (Sandbox Code Playgroud)
无论如何都不优雅。我个人创建了一个对象,window其中包含有关构建的各种信息(时间、版本和发布摘要链接)。
要保持更“纯”,请将{git-hash}字符串environment.prod.ts插入并sed针对main-*.js生成的所有文件运行。
"postbuild": "sed -i '' \"s/{git\\-hash}/$(git rev-parse --short HEAD)/g\" dist/*/main-*.js"
Run Code Online (Sandbox Code Playgroud)
请注意,您将始终看到 '{git-hash}' 在本地运行,因为它仅在构建后被替换。如果您在构建之前替换它,显然不能在本地将来的构建中替换它,并且肯定会不小心将其签入。
- - 更新 - -
最终创建了一个库来提取各种信息。最终只使用了版本、构建时间和提交时间。
https://www.npmjs.com/package/@rippell/ngx-build-info
我有一些不同的方法,灵感来自主项目目录中的答案repo Seba Arce和Jeroen:
npm install git-rev-sync --save这个库可以访问哈希和分支名称)git-version-gen.js具有以下正文的文件const git = require('git-rev-sync');
const { writeFileSync } = require('fs');
const gitInfo = { commit: git.short(), commitLong: git.long(), branch: git.branch() };
const ts = 'export const gitVersion = ' + JSON.stringify(gitInfo, null, 2);
writeFileSync('src/environments/git-version.ts', ts);Run Code Online (Sandbox Code Playgroud)
package.json中scripts加"build": "node git-version-gen.js && ng build ..."app.component.ts按如下方式使用它import { gitVersion } from '../../../environments/git-version';
// ...
constructor() {
console.log(`GIT branch:`,gitVersion.branch);
console.log(`GIT commit:`,gitVersion.commit);
}Run Code Online (Sandbox Code Playgroud)
使用这个有什么好处?
我们在此处创建src/environments/git-version.ts文件,因此这是 TypeScript,而不是 .json - 类似于您的环境文件 - 这将开启您的代码编辑器(例如 VSCode)的支持
您可以访问提交哈希和分支名称(libgit-describe不提供对分支名称的访问权限)
如果您提交生成的git-version.ts文件而不是将其放入,.gitignore那么项目将在没有构建的情况下运行(例如 by ng serve ...),并且新的开发人员不会因为缺少一些“神秘”文件而感到困惑...... - 但是选择取决于您。
跨平台 - 在 Azure (windows)、MacOs (~linux-like) 上测试
| 归档时间: |
|
| 查看次数: |
10172 次 |
| 最近记录: |