checkwxss.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. const path = require('path')
  2. const through = require('through2')
  3. const Vinyl = require('vinyl')
  4. const _ = require('./utils')
  5. /**
  6. * 获取 import 列表
  7. */
  8. function getImportList(wxss, filePath) {
  9. const reg = /@import\s+(?:(?:"([^"]+)")|(?:'([^']+)'));/ig
  10. const importList = []
  11. let execRes = reg.exec(wxss)
  12. while (execRes && (execRes[1] || execRes[2])) {
  13. importList.push({
  14. code: execRes[0],
  15. path: path.join(path.dirname(filePath), execRes[1] || execRes[2]),
  16. })
  17. execRes = reg.exec(wxss)
  18. }
  19. return importList
  20. }
  21. /**
  22. * 获取 wxss 内容
  23. */
  24. async function getContent(wxss, filePath, cwd) {
  25. let importList = []
  26. if (wxss) {
  27. const currentImportList = getImportList(wxss, filePath)
  28. for (const item of currentImportList) {
  29. // 替换掉 import 语句,不让 less 编译
  30. wxss = wxss.replace(item.code, `/* *updated for miniprogram-custom-component* ${item.code} */`)
  31. // 处理依赖的 wxss
  32. const importWxss = await _.readFile(item.path)
  33. const importInfo = await getContent(importWxss, item.path, cwd)
  34. // 获取依赖列表
  35. importList.push(new Vinyl({
  36. cwd,
  37. path: item.path,
  38. contents: Buffer.from(importInfo.wxss, 'utf8'),
  39. }))
  40. importList = importList.concat(importInfo.importList)
  41. }
  42. }
  43. return {
  44. wxss,
  45. importList,
  46. }
  47. }
  48. module.exports = {
  49. start() {
  50. return through.obj(function (file, enc, cb) {
  51. if (file.isBuffer()) {
  52. getContent(file.contents.toString('utf8'), file.path, file.cwd).then(res => {
  53. const {wxss, importList} = res
  54. importList.forEach(importFile => this.push(importFile))
  55. file.contents = Buffer.from(wxss, 'utf8')
  56. this.push(file)
  57. // eslint-disable-next-line promise/no-callback-in-promise
  58. cb()
  59. }).catch(err => {
  60. // eslint-disable-next-line no-console
  61. console.warn(`deal with ${file.path} failed: ${err.stack}`)
  62. this.push(file)
  63. // eslint-disable-next-line promise/no-callback-in-promise
  64. cb()
  65. })
  66. } else {
  67. this.push(file)
  68. cb()
  69. }
  70. })
  71. },
  72. end() {
  73. return through.obj(function (file, enc, cb) {
  74. if (file.isBuffer) {
  75. const reg = /\/\*\s\*updated for miniprogram-custom-component\*\s(@import\s+(?:(?:"([^"]+)")|(?:'([^"]+)'));)\s\*\//ig
  76. const wxss = file.contents.toString('utf8').replace(reg, (all, $1) => $1)
  77. file.contents = Buffer.from(wxss, 'utf8')
  78. this.push(file)
  79. cb()
  80. } else {
  81. this.push(file)
  82. cb()
  83. }
  84. })
  85. },
  86. }