公司項目使用webpack+gitlab,打包發佈採用Jenkins自動化部署。天天都會發布多個版本,有時遇到問題須要知道前端包的版本信息。因爲項目是從零開始,並無此功能。
因此本文介紹如何編寫webpack插件,用於打包時自動記錄信息。姑且稱此插件爲RecordBuildInfoPlugin
。前端
很簡單,只須要3步,便可實現。webpack
在build
文件夾下新建文件record-build-info-plugin.js
,內容以下:git
const childProcess = require('child_process') const os = require('os') const fs = require('fs') const VERSION_FILE_PATH = 'dist/static/build-info.json' class RecordBuildInfoPlugin { constructor () { this.buildInfo = this.getBuildInfo() } getBuildInfo () { const commit = childProcess.execSync('git show -s --format=%H').toString().trim() const commitDateObj = new Date(childProcess.execSync(`git show -s --format=%cd`).toString()) const commitDateTime = commitDateObj.toLocaleDateString() + ' ' + commitDateObj.toLocaleTimeString() const now = new Date() const buildDateTime = now.toLocaleDateString() + ' ' + now.toLocaleTimeString() const ipAddress = getIPAddress() return { commit, commitDateTime, buildDateTime, ipAddress } } saveBuildInfo () { fs.writeFileSync(VERSION_FILE_PATH, JSON.stringify(this.buildInfo)) } apply (compiler) { if (compiler && compiler.hooks && compiler.hooks.done && compiler.hooks.done.tap) { // webpack 4.x compiler.hooks.done.tap('RecordBuildInfoPlugin', () => { this.saveBuildInfo() }) } else if (compiler && compiler.plugin) { // webpack 3.x compiler.plugin('done', () => { this.saveBuildInfo() }) } else { console.error('RecordBuildInfoPlugin Error') } } } function getIPAddress () { var interfaces = os.networkInterfaces() let ipArr = [] for (let devName in interfaces) { let iface = interfaces[devName] for (let i = 0; i < iface.length; i++) { let alias = iface[i] if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { ipArr.push(alias.address) } } } return (ipArr.length ? ipArr : 'Fail Get IP') } module.exports = RecordBuildInfoPlugin
webpack.prod.conf.js
文件中引用這個pluginconst RecordBuildInfoPlugin = require('./record-build-info-plugin') const webpackConfig = merge(baseWebpackConfig, { plugins: [ // 在末尾處引用 new RecordBuildInfoPlugin() ] })
npm run build
在dist/static
下會多出json文件,記錄打包信息。web
apply
方法,在apply
方法中去實現本身想作的事情。