如何将 git hash 添加到 Vue.js 组件

use*_*018 9 git heroku node.js vue.js vue-component

我想创建一个 vue.js 组件,它将显示最近 git 提交的 package.json 版本号和哈希值。这是到目前为止的代码:

<template>
  <div class="versionLabel">Version: {{version}} (HASH)</div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { version } from '../../package.json';

@Component
export default class VersionLabel extends Vue {
  get version() {
    return version;
  }
}
</script>

<style scoped lang="scss">
div {
  background-color: rgb(60, 172, 60);
  color: lightgray;
}
</style>
Run Code Online (Sandbox Code Playgroud)

我正在使用命令部署到 Heroku

"postinstall": "if test \"$NODE_ENV\" = \"production\" ; then npm run build ; fi ",
"start": "node server.js",
Run Code Online (Sandbox Code Playgroud)

在 package.json 和这个简单的服务器中:

const express = require('express');
const serveStatic = require("serve-static")

app = express();
app.use(serveStatic(__dirname + '/dist'));

const port = process.env.PORT || 5000;
app.listen(port);
Run Code Online (Sandbox Code Playgroud)

版本号正在工作(尽管欢迎提出改进建议)但是如何添加 git hash 来代替 HASH?

Pio*_*dal 16

安装git-describe作为开发依赖项(例如yarn add --dev git-describe)。

另外vue.config.js

const {gitDescribe, gitDescribeSync} = require('git-describe');
process.env.VUE_APP_GIT_HASH = gitDescribeSync().hash
Run Code Online (Sandbox Code Playgroud)

现在,在每个组件中,我们都有process.env.VUE_APP_GIT_HASH变量。

这是我将它添加到我的应用程序的方式:https : //github.com/Quantum-Game/quantum-game-2/pull/164(有一些讨论)。

其他方法

还有其他方法,例如使用git-revision-webpack-pluginVue 论坛的示例):

const GitRevisionPlugin = require('git-revision-webpack-plugin')

module.exports = {
  'chainWebpack': config => {
    config.plugin('define').tap(args => {
      const gitRevisionPlugin = new GitRevisionPlugin()
      args[0]['process.env']['VUE_APP_COMMIT_HASH'] = JSON.stringify(gitRevisionPlugin.commithash())
      return args
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是直接使用 git 和child-process

也可以看看


Eri*_*ric 5

我不熟悉 Heroku,但是我希望我的解决方案的某些部分对您有用。

我正在开发一个 vue 应用程序,我使用 GitLab CI/CD 并将其部署到 AWS 上的 S3 存储桶,然后与 cloudfront 一起分发。有时,我们的客户会要求进行已经做出的更改。因此,为了防止混淆,我想在应用程序的页脚中包含一个 git 哈希,以便我们可以快速检查他们是否正在查看应用程序的最新版本。

在我的.gitlab-ci.yml文件中,我包含了以下 bash 命令:

hash=`git describe --always`
echo "\"$hash\"" > src/assets/hash.json
Run Code Online (Sandbox Code Playgroud)

这将创建一个hash.json文件,该文件的唯一内容是作为字符串的最新提交哈希。例如"015d8f1"

我假设当你部署到 Heroku 时,有一种类似的方式来执行 bash 命令。

从那里您可以在任何组件中读取该文件并将其用作数据。例如

<script>
import GitHash from "@/assets/hash.json";

export default {
  name: "TheFooter",
  data() {
    return {
      GitHash: GitHash
    };
  }
};
</script>
Run Code Online (Sandbox Code Playgroud)