remind-production-api-url.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * 生产发版 / 编译前提醒:检查 config/env.js 的 APP_ENV。
  3. * - 默认:仅打印醒目提醒(不中断)。
  4. * - 严格:`node scripts/remind-production-api-url.mjs --strict`
  5. * 若 APP_ENV 不是 production,或生产 API 仍含本机地址,则 exit 1。
  6. */
  7. import fs from 'node:fs'
  8. import path from 'node:path'
  9. import { fileURLToPath } from 'node:url'
  10. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  11. const root = path.resolve(__dirname, '..')
  12. const envPath = path.join(root, 'config', 'env.js')
  13. const banner = () => {
  14. const lines = [
  15. '',
  16. '================================================================',
  17. ' shanxia miniprogram 发版提醒',
  18. ' 部署到生产环境前,必须修改 config/env.js:',
  19. " export const APP_ENV = 'production'",
  20. ' 生产 API:https://w.shanxiachem.com/api',
  21. ' 生产静态:https://w.shanxiachem.com/shanxia-static/',
  22. ' 微信合法域名请配置:w.shanxiachem.com',
  23. '================================================================',
  24. ''
  25. ]
  26. console.warn('\x1b[33m%s\x1b[0m', lines.join('\n'))
  27. }
  28. const readAppEnv = (raw) => {
  29. const m = raw.match(/export\s+const\s+APP_ENV\s*=\s*['"]([^'"]+)['"]/)
  30. return m ? m[1] : ''
  31. }
  32. const productionBlockLooksLocal = (raw) => {
  33. // 只检查 production 预设块内是否误写本机地址
  34. const m = raw.match(/production:\s*\{([\s\S]*?)\n\s*\}/)
  35. if (!m) return false
  36. return /127\.0\.0\.1|localhost/.test(m[1])
  37. }
  38. const strictCheck = () => {
  39. const raw = fs.readFileSync(envPath, 'utf8')
  40. const appEnv = readAppEnv(raw)
  41. if (appEnv !== 'production') {
  42. console.error(
  43. `\x1b[31m[release-check]\x1b[0m config/env.js 中 APP_ENV='${appEnv || '?'}',发版须改为 'production'。`
  44. )
  45. process.exit(1)
  46. }
  47. if (productionBlockLooksLocal(raw)) {
  48. console.error(
  49. '\x1b[31m[release-check]\x1b[0m production 预设中仍含 127.0.0.1 / localhost,请先修正。'
  50. )
  51. process.exit(1)
  52. }
  53. if (!/https:\/\/w\.shanxiachem\.com\/api/.test(raw)) {
  54. console.error(
  55. '\x1b[31m[release-check]\x1b[0m 未在 env.js 中发现生产 API https://w.shanxiachem.com/api。'
  56. )
  57. process.exit(1)
  58. }
  59. console.warn('\x1b[32m[release-check]\x1b[0m APP_ENV=production,生产 API 配置检查通过。')
  60. }
  61. banner()
  62. const strict = process.argv.includes('--strict')
  63. if (strict) strictCheck()