Including git commit hash and date in webpack build

前端 未结 3 877
半阙折子戏
半阙折子戏 2021-02-01 01:04

I\'m using react/es6/webpack. I want to show the date of the build and git hash somewhere in my app. What\'s the best approach?

相关标签:
3条回答
  • 2021-02-01 01:38

    Another way of doing this is ( in ANGULAR + REACT ) :

    Just install this package git-revision-webpack-plugin

    Simple webpack plugin that generates VERSION and COMMITHASH files during build based on a local git repository.


    Sample Code :

    Inside your webpack.config.js (or any dev - prod file)

    const GitRevisionPlugin = require('git-revision-webpack-plugin');
    const gitRevisionPlugin = new GitRevisionPlugin();
    
    plugins: [
        new DefinePlugin({
          'VERSION': JSON.stringify(gitRevisionPlugin.version()),
          'COMMITHASH': JSON.stringify(gitRevisionPlugin.commithash()),
          'BRANCH': JSON.stringify(gitRevisionPlugin.branch()),
        }),
      ]
    

    In your Component (React):

    export class Home extends Component{
        ....
    
        render() {
            return(
                <div>
                    {VERSION} 
                    {COMMITHASH}
                    {BRANCH}
                </div>
            )
        }
    }
    

    In your Template (Angular):

    {{ VERSION }} 
    {{ COMMITHASH }}
    {{ BRANCH }}
    
    0 讨论(0)
  • 2021-02-01 01:39

    You can use webpack's DefinePlugin:

    // get git info from command line
    let commitHash = require('child_process')
      .execSync('git rev-parse --short HEAD')
      .toString();
    
    ...
    plugins: [
        new webpack.DefinePlugin({
          __COMMIT_HASH__: JSON.stringify(commitHash),
        })
      ]
    ...
    

    Then you can use it in your app with __COMMIT_HASH__

    0 讨论(0)
  • 2021-02-01 02:02

    I couldn't comment to the top post, so here goes:

    Webpack.dev.js

    import gitprocess from "child_process"
    let LoadCommitDate = gitprocess
      .execSync('git log -1 --date=format:"%Y/%m/%d %T" --format="%ad"')
      .toString()
    ...
    plugins: [
        new webpack.DefinePlugin({
           COMMITDATE: JSON.stringify(LoadCommitDate),
        })
      ]
    

    Additionally in .eslintrc

      "globals": {
        "COMMITDATE": "readonly",
      },
    

    Result - latest commit date you can reference in your code!

    console.log(COMMITDATE)
    2020/05/04 21:02:03
    
    0 讨论(0)
提交回复
热议问题