sync-static-public-urls.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * 将「当前选用的静态基址」写入 pages.json、index.html。
  3. * - 目标基址:`STATIC_ASSETS_BASE_URL` 环境变量,否则取 `static-assets-defaults.js` 中 **STATIC_ASSETS_BASE_URL_TEST**。
  4. * - 若文件中仍是更旧的 CDN 前缀,可一次性指定 `PREV_STATIC_ASSETS_BASE_URL`(要整段替换掉的前缀,须以 / 结尾),例如:
  5. * `PREV_STATIC_ASSETS_BASE_URL=https://old-host/sqxp-static/ npm run sync-static-public-urls`
  6. * 不设则仅把「与目标相同」视为已就绪,不做无意义的替换。
  7. *
  8. * 生产发版:先设 `STATIC_ASSETS_BASE_URL` 为生产根地址再执行。
  9. * 用法:在 sqxp-wx 根目录执行 `npm run sync-static-public-urls`
  10. */
  11. import fs from 'node:fs'
  12. import path from 'node:path'
  13. import { fileURLToPath } from 'node:url'
  14. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  15. const root = path.resolve(__dirname, '..')
  16. const defaultsPath = path.join(root, 'config/static-assets-defaults.js')
  17. const raw = fs.readFileSync(defaultsPath, 'utf8')
  18. const pick = (name) => {
  19. const m = raw.match(new RegExp(`export const ${name}\\s*=\\s*['"]([^'"]+)['"]`))
  20. return m?.[1]?.trim() || ''
  21. }
  22. const testBase = pick('STATIC_ASSETS_BASE_URL_TEST') || pick('STATIC_ASSETS_BASE_URL_DEFAULT')
  23. const fromFile = testBase || process.env.VITE_STATIC_ASSETS_BASE_URL || 'https://REPLACE_TEST_STATIC_HOST/shanxia-static/'
  24. const normalized = (() => {
  25. const b = (process.env.STATIC_ASSETS_BASE_URL || fromFile).trim()
  26. return b.endsWith('/') ? b : `${b}/`
  27. })()
  28. const prevRaw = process.env.PREV_STATIC_ASSETS_BASE_URL?.trim()
  29. const prev = prevRaw
  30. ? prevRaw.endsWith('/') ? prevRaw : `${prevRaw}/`
  31. : normalized
  32. for (const rel of ['pages.json', 'index.html']) {
  33. const p = path.join(root, rel)
  34. if (!fs.existsSync(p)) continue
  35. let s = fs.readFileSync(p, 'utf8')
  36. if (prev !== normalized) {
  37. s = s.split(prev).join(normalized)
  38. }
  39. fs.writeFileSync(p, s)
  40. }
  41. if (prev === normalized) {
  42. console.log('Static base:', normalized, '(未设置 PREV_STATIC_ASSETS_BASE_URL,未执行旧前缀替换)')
  43. } else {
  44. console.log('Static base set to:', normalized, '(replaced prefix:', prev + ')')
  45. }