【问题标题】:How to add git hash to Vue.js Component如何将 git hash 添加到 Vue.js 组件
【发布时间】:2019-05-26 12:26:21
【问题描述】:

我想创建一个 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>

我正在使用命令部署到 Heroku

"postinstall": "if test \"$NODE_ENV\" = \"production\" ; then npm run build ; fi ",
"start": "node server.js",

在 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);

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

【问题讨论】:

  • 我不认为它是重复的。这很有帮助,但需要在节点服务器上运行。我如何将结果传递给 vue 组件?
  • 您使用什么来构建 Vue.js 应用程序?是vue-cli 项目吗?
  • 是的。命令是:vue-cli-service build

标签: node.js git heroku vue.js vue-component


【解决方案1】:

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

vue.config.js 添加:

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

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

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

其他方法

还有其他方法,例如使用git-revision-webpack-pluginthe Vue forum 的示例):

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
    })
  }
}

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

另见

【讨论】:

    【解决方案2】:

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

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

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

    hash=`git describe --always`
    echo "\"$hash\"" > src/assets/hash.json
    

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

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

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

    <script>
    import GitHash from "@/assets/hash.json";
    
    export default {
      name: "TheFooter",
      data() {
        return {
          GitHash: GitHash
        };
      }
    };
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 2019-09-19
      • 2023-03-15
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2018-06-28
      • 2016-04-11
      相关资源
      最近更新 更多