px2Rpx.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import util from 'gulp-util'
  2. import through2 from 'through2'
  3. /**
  4. * 自定义插件 - px to rpx
  5. */
  6. const px2Rpx = () => {
  7. // 正则匹配
  8. const pxReplace = (value = '') => {
  9. const pxRegExp = /"[^"]+"|'[^']+'|url\([^\)]+\)|(\d*\.?\d+)px/g
  10. const pxReplace = (m, $1) => {
  11. if (!$1) return m
  12. const pixels = parseFloat(m)
  13. return pixels === 0 ? 0 : `${2 * pixels}rpx`
  14. }
  15. return value.replace(pxRegExp, pxReplace)
  16. }
  17. return through2.obj(function(file, encoding, cb) {
  18. // 如果文件为空,不做任何操作,转入下一个操作,即下一个pipe
  19. if (file.isNull()) {
  20. this.push(file)
  21. return cb()
  22. }
  23. // 插件不支持对stream直接操作,抛出异常
  24. if (file.isStream()) {
  25. this.emit('error', new util.PluginError('px2Rpx', 'Streaming not supported'))
  26. return cb()
  27. }
  28. // 内容转换,处理好后,再转成 Buffer 形式
  29. const content = pxReplace(file.contents.toString())
  30. file.contents = typeof Buffer.from === 'function' ? Buffer.from(content) : new Buffer(content)
  31. // 下面这两句基本是标配,可参考 through2 的 API
  32. this.push(file)
  33. cb()
  34. })
  35. }
  36. export default px2Rpx