如何使用webpack注入内部版本号?

时间:2014-07-09 20:24:16

标签: webpack

我想在我的项目中注入构建号和版本信息,因为它是用webpack构建的。例如,以便我的代码可以执行以下操作:

var buildInfo = require("build-info");

在构建时生成build-info模块的最佳方法是什么?

7 个答案:

答案 0 :(得分:53)

您可以使用DefinePlugin来使您的构建信息与代码内联:

<强>配置

new webpack.DefinePlugin({
   __VERSION__: JSON.stringify('12345')
})

应用代码

console.log(__VERSION__);

答案 1 :(得分:15)

我会做更多更简单,只需使用npm version patch (npm-version) (无需插件)

package.json (构建前的路径版本示例)

{
  "version": "1.0.0",
  "scripts": {
    "build": "npm version patch && node build/build.js"
  }
}

因此,当您运行npm run build时,这会修补您的package.json中的版本(1.0.01.0.1

加分:您也可以将其添加到配置(示例config/prod.env.js

'use strict'
const pkg = require('./package.json')
module.exports = {
  NODE_ENV: '"production"',
  VERSION: pkg.version
}

然后你可以在我们的JS

中的任何地方使用process.env.VERSION

已更新:just use process.env.npm_package_version,无需包含package.json

答案 2 :(得分:13)

有一个从package.json自动注入版本的插件。 它可以将它作为注释注入html,css,js,也可以作为特殊标记的值 https://www.npmjs.com/package/webpack-auto-inject-version

如何:

首先,您必须将其添加到您的项目中:

npm i webpack-auto-inject-version

然后你需要设置你的webpack配置:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
    plugins: [
        new WebpackAutoInject()
    ]
}

由于您要将其注入javascript,您应该在javascript文件中添加一个标记(在webpack编译期间将更改为版本)

var version = '[AIV]{version}[/AIV]';
console.log(version);

自动增加:

您可以将其设置为直接从webpack自动增加版本:

webpack --other-webpack-settings --major

webpack --other-webpack-settings -- minor

webpack --other-webpack-settings --patch

其中--other-webpack-settings等于您的自定义行args。 简化 - 无论何时想要自动增加版本,都需要--major, - minor或--patch。

答案 3 :(得分:6)

这是我的食谱,源自这个问题的其他答案。这使用了WebpackVersionFilePluginexeca,现在对我很有用。

通过npm:

安装插件
npm install webpack-version-file-plugin --save-dev
npm install execa --save-dev

<强> webpack.config.js:

const WebpackVersionFilePlugin = require('webpack-version-file-plugin');
const execa = require('execa');

const gitHash = execa.sync('git', ['rev-parse', '--short', 'HEAD']).stdout;
const gitNumCommits = Number(execa.sync('git', ['rev-list', 'HEAD', '--count']).stdout);
const gitDirty = execa.sync('git', ['status', '-s', '-uall']).stdout.length > 0;

module.exports = {
// ... snip ...
plugins: [
    new WebpackVersionFilePlugin({
        packageFile: path.join(__dirname, 'package.json'),
        template: path.join(__dirname, 'version.ejs'),
        outputFile: path.join('build/ts/', 'version.json'),
        extras: {
            'githash': gitHash,
            'gitNumCommits': gitNumCommits,
            'timestamp': Date.now(),
            'dirty': gitDirty
        }
    }),
// ... snip ...

version.ejs (在项目根目录中):

{
    "name":       "<%= package.name %>",
    "buildDate":  <%= extras.timestamp %>,
    "version":    "<%= package.version %>",
    "numCommits": <%= extras.gitNumCommits %>,
    "hash":       "<%= extras.githash %>",
    "dirty":      <%= extras.dirty %>
}

到目前为止,运行此操作会在build/ts中使用此内容获取一个version.json文件:

{
    "name":       "app name from package.json",
    "buildDate":  1518774257225,
    "version":    "2.0.1",
    "numCommits": 148,
    "hash":       "5a74b7a",
    "dirty":      false
}

dirty标志表示构建是否包含未提交或未跟踪的更改。

我使用TypeScript,因此下面介绍如何将JSON文件转换为我的TypeScript代码。如果您没有TypeScript,我们仍然将问题简化为读取JSON文件。 : - )

<强> app.ts:

import * as appVersionJson from './version.json';

export const appVersion: AppVersion = <any>appVersionJson;

export interface AppVersion {
    /** application name as specified in package.json */
    readonly name: string;

    /** build timestamp in milliseconds since the epoch */
    readonly buildDate: number;

    /** application version as specified in package.json */
    readonly version: string;

    /** number of commits in the Git repo */
    readonly numCommits: number;

    /** latest Git commit hash */
    readonly hash: string;

    /** flag is set when uncommitted or untracked changes are present in the workspace */
    readonly dirty: boolean;
}

// ...snip...
// now just use it in methods, for example:
appVersion.version + '.' + appVersion.numCommits + ' (' + appVersion.hash + ')'

好的 - 希望这提供了一些关于如何在代码中提供良好的构建号信息的线索。顺便说一句,npm version是一个很好的方法来突破版本号,就像这样工作。

答案 4 :(得分:3)

我有两个我分发的文件,它们都是从git和npm(package.json)的角度来看的。我仍然想在meta标签中将其拉入我的index.template.html,但还没有想到(我怎样才能从文件内容或cmd输出中创建DEFINE?)。 / p>

对于git,我使用webpack-shell-plugin创建一个带有git信息的文件:

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']
    }),

对于npm,我添加npm版本命令(&#34; npm版本patch / minor / major&#34;)到(1)确保git中没有未完成的未提交更改 - 如果有任何和(如果有) 2)更新package.json版本并将其检入git。

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

然后我使用记录不完整的,可能是错误的WebpackVersionFilePlugin来分发它。

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

在顶层目录中使用此模板:

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

&#34; package.name&#34;也不是&#34;名称&#34;工作

结果是我的./dist/directory中有两个文件。 gitversion.txt(branch,commit,count from head):

fmwk/feathers
9cfe791a09d3d748e8120e0628
51

和version.json:

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

答案 5 :(得分:0)

我无法使它与TypeScript一起使用,因此我通过在每次编译时创建一个文件来帮助自己。

webpack.config.js

const fs = require('fs'); 
const path = require('path'); 
fs.writeFileSync(path.resolve(path.join(__dirname, 'src/version.ts')), 
`// This file is auto-generated by the build system. 
const BundleVersion = "${ new Date().toISOString().substr(0, 10) }"; 
export default BundleVersion; 
`); 

那我就是 import BundleVersion from './version'; 并确保它确实在某个地方使用(console.log或将其暴露在某个地方),所以它不会被摇晃,就是这样,捆绑包中的时间戳(或版本),在编译时创建(直接从此处开始)读取package.json并根据需要使用软件包版本)。

答案 6 :(得分:0)

我制作了一个webpack加载器,将构建信息注入到自动生成的文件中。您可以找到它13b8f68c1f

安装后,您可以像这样使用它:

cmd_blame

有关更多信息,请访问merge