1

背景

公司项目使用webpack+gitlab,打包发布采用Jenkins自动化部署。每天都会发布多个版本,有时遇到问题需要知道前端包的版本信息。由于项目是从零开始,并没有此功能。
所以本文介绍如何编写webpack插件,用于打包时自动记录信息。姑且称此插件为RecordBuildInfoPlugin

How To Do

很简单,只需要3步,即可实现。

1. 编写webpack插件文件

build文件夹下新建文件record-build-info-plugin.js,内容如下:

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

2. 在webpack.prod.conf.js文件中引用这个plugin

const RecordBuildInfoPlugin = require('./record-build-info-plugin')
const webpackConfig = merge(baseWebpackConfig, {
  plugins: [
    // 在末尾处引用
    new RecordBuildInfoPlugin()
  ]
})

3. 最后验证

npm run build

dist/static下会多出json文件,记录打包信息。

总结

  • webpack的插件,就是新建一个class,引用后webpack会调用此类的apply方法,在apply方法中去实现自己想做的事情。
  • 本文只是抛砖引玉,除了代码里记录的各种信息外,还可以干很多事情。希望看完本文后,你可以快速地完成自己的webpack plugin。

davidshi
33 声望6 粉丝

Deliver Happiness


« 上一篇
VLAN