build_cache.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const fs = require('fs')
  2. const path = require('path')
  3. let dir = path.join(__dirname, 'dist')
  4. let list = walk(dir)
  5. if (process.env.URL === 'new') {
  6. global.URL_CDN = '//static.meechat.me/cdn/new.mee.chat/'
  7. } else if (process.env.URL === 'form') {
  8. global.URL_CDN = '//static.meechat.me/cdn/mee.chat/'
  9. } else {
  10. global.URL_CDN = '/'
  11. }
  12. // console.log(global.URL_CDN)
  13. // console.log(dir)
  14. // 获取文件
  15. let baseDir = path.join(__dirname, '/')
  16. list.forEach((value, index) => {
  17. // 对.html和.json特殊处理
  18. if (value.endsWith('.html') || value.endsWith('.json')) {
  19. value = value.replace(baseDir, '/')
  20. list[index] = value.replace('/dist/', '/')
  21. } else {
  22. value = value.replace(baseDir, '')
  23. list[index] = global.URL_CDN + value
  24. }
  25. })
  26. let fileName = dir + '/sw.js'
  27. console.log(list)
  28. // 修改文件
  29. fs.readFile(fileName, 'utf8', function (err, files) {
  30. if (!err) {
  31. let result = files.replace('let urlsToCache = []', 'let urlsToCache = ' + JSON.stringify(list) + '')
  32. fs.writeFile(fileName, result, 'utf8', function (err) {
  33. if (err) return console.log(err)
  34. })
  35. }
  36. })
  37. function walk (dir) {
  38. var children = []
  39. fs.readdirSync(dir).forEach(function (filename) {
  40. var path = dir + '/' + filename
  41. var stat = fs.statSync(path)
  42. if (stat && stat.isDirectory()) {
  43. children = children.concat(walk(path))
  44. } else {
  45. children.push(path)
  46. }
  47. })
  48. return children
  49. }