build_cache.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // 修改文件
  28. fs.readFile(fileName, 'utf8', function (err, files) {
  29. if (!err) {
  30. let result = files.replace('let urlsToCache = []', 'let urlsToCache = ' + JSON.stringify(list) + '')
  31. fs.writeFile(fileName, result, 'utf8', function (err) {
  32. if (err) return console.log(err)
  33. })
  34. }
  35. })
  36. function walk (dir) {
  37. var children = []
  38. fs.readdirSync(dir).forEach(function (filename) {
  39. var path = dir + '/' + filename
  40. var stat = fs.statSync(path)
  41. if (stat && stat.isDirectory()) {
  42. children = children.concat(walk(path))
  43. } else {
  44. children.push(path)
  45. }
  46. })
  47. return children
  48. }