How can I inject a build number with webpack?

后端 未结 7 964
野的像风
野的像风 2021-01-30 10:38

I\'d like to inject a build number and version information to my project as it\'s built with webpack. For example, so that my code can do something like:

var bui         


        
7条回答
  •  粉色の甜心
    2021-01-30 10:56

    I have two files that I distribute that have the build number from the viewpoint of both git and npm (package.json). I'd still like to pull this into my index.template.html in a meta tag, but haven't figured that out yet (how can I make a DEFINE from file contents or a cmd output?).

    For git, I use webpack-shell-plugin to make a file with the git info:

    const WebpackVersionFilePlugin = require('webpack-version-file-plugin');
    plugins: [
    new WebpackShellPlugin({
          onBuildStart: [
            'git name-rev --name-only HEAD > dist/gitversion.txt',
            'git rev-list HEAD --count >> dist/gitversion.txt',
            'git rev-parse HEAD >> dist/gitversion.txt']
        }),
    

    For npm, I add the npm version command ("npm version patch/minor/major") to (1) ensure there is no outstanding uncommitted changes in git - it fails if there are any and (2) update the package.json version and check it into git.

      "scripts": {
        "build": "npm run lint && npm run init && npm version patch && webpack --config webpack.config.js",
    

    I then distribute that using poorly documented, probably buggy, WebpackVersionFilePlugin.

    const WebpackVersionFilePlugin = require('webpack-version-file-plugin');
    new WebpackVersionFilePlugin({
          packageFile:path.join(__dirname, 'package.json'),
          outputFile: path.join('./dist/', 'version.json')
        }),
    

    Using this template in the top directory:

    {
      "version" : {
        "name":      "<% package.name %>",
        "buildDate": "<%= currentTime %>",
        "version":   "<%= package.version %>"
      }
    }
    

    Neither "package.name" nor "name" work.

    The result is two files in my ./dist/directory. gitversion.txt (branch, commit, count from head):

    fmwk/feathers
    9cfe791a09d3d748e8120e0628
    51
    

    and version.json:

    {
      "version" : {
        "name":      "",
        "buildDate": "Fri Oct 21 2016 11:10:12 GMT+0800 (PHT)",
        "version":   "0.6.2"
      }
    }
    

提交回复
热议问题