UNPKG

snapshot-build-hash-webpack-plugin

Version:

A Webpack plugin which take build hash and append to current version in package.json

71 lines (56 loc) 2.36 kB
const path = require('path'); const gitBranchIs = require('git-branch-is'); const validateOptions = require('schema-utils'); const schema = { type: 'object', properties: { root: { type: 'string' } } }; class SnapshotBuildHashPlugin { constructor(options = { root: path.dirname(path.dirname(__dirname)) }) { validateOptions(schema, options, 'SnapshotBuildHashPlugin'); this.options = options; } apply(compiler) { const { root } = this.options const packagePath = path.resolve(root, 'package.json') const packageLockPath = path.resolve(root, 'package-lock.json') let packageFile = require(packagePath) let packageLockFile = require(packageLockPath) const currentVersion = packageFile.version compiler.hooks.afterEmit.tapAsync('SnapshotBuildHashPlugin', (compilation, callback) => { const stats = compilation.getStats().toJson({ hash: true, publicPath: false, assets: false, chunks: false, modules: false, source: false, errorDetails: false, timings: false }); gitBranchIs(branchName => /^master$|^release$|^hotfix/.test(branchName)).then( result => { if (!result) { const release = /^([0-9]\.[0-9]\.[0-9])($|-SNAPSHOT.*$)/.exec(currentVersion) if (release) { const version = `${release[1]}-SNAPSHOT.${stats.hash}` packageFile.version = version packageLockFile.version = version compiler.outputFileSystem.writeFile(packagePath, JSON.stringify(packageFile, null, 2), () => { compiler.outputFileSystem.writeFile(packageLockPath, JSON.stringify(packageLockFile, null, 2), callback); }); } } else { callback() } }, err => console.error(err) ) }); } } module.exports = SnapshotBuildHashPlugin;