remind-production-api-url.mjs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. * 上传微信前务必执行:npm run release:check-api
  8. */
  9. import fs from 'node:fs'
  10. import path from 'node:path'
  11. import { fileURLToPath } from 'node:url'
  12. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  13. const root = path.resolve(__dirname, '..')
  14. const envPath = path.join(root, 'config', 'env.js')
  15. const readAppEnv = (raw) => {
  16. // 只认行首 export,避免命中注释里的示例「APP_ENV = 'production'」
  17. const m = raw.match(/^export\s+const\s+APP_ENV\s*=\s*['"]([^'"]+)['"]/m)
  18. return m ? m[1] : ''
  19. }
  20. const productionBlockLooksLocal = (raw) => {
  21. const m = raw.match(/production:\s*\{([\s\S]*?)\n\s*\}/)
  22. if (!m) return false
  23. return /127\.0\.0\.1|localhost/.test(m[1])
  24. }
  25. const raw = fs.readFileSync(envPath, 'utf8')
  26. const appEnv = readAppEnv(raw) || '?'
  27. const color =
  28. appEnv === 'production' ? '\x1b[32m' : appEnv === 'local' ? '\x1b[31m' : '\x1b[33m'
  29. const reset = '\x1b[0m'
  30. console.log(
  31. [
  32. '',
  33. '╔════════════════════════════════════════════════════════════╗',
  34. `║ 当前小程序 APP_ENV = ${appEnv.padEnd(36)}║`,
  35. appEnv === 'production'
  36. ? '║ ✅ 生产配置 ║'
  37. : '║ ⚠️ 非生产!正式上传微信前请改为 production ║',
  38. '║ 文件:config/env.js ║',
  39. '║ 检查:npm run release:check-api ║',
  40. '╚════════════════════════════════════════════════════════════╝',
  41. ''
  42. ].join('\n').replace(/^/gm, color) + reset
  43. )
  44. if (appEnv !== 'production') {
  45. console.warn(
  46. '\x1b[33m%s\x1b[0m',
  47. [
  48. '发版步骤:',
  49. " 1. 修改 config/env.js → export const APP_ENV = 'production'",
  50. ' 2. npm run release:check-api(必须通过)',
  51. ' 3. HBuilderX:发行 → 小程序-微信 → 再上传',
  52. ''
  53. ].join('\n')
  54. )
  55. }
  56. const strict = process.argv.includes('--strict')
  57. if (strict) {
  58. if (appEnv !== 'production') {
  59. console.error(
  60. `\x1b[31m[release-check]\x1b[0m APP_ENV='${appEnv}',发版须改为 'production'。`
  61. )
  62. process.exit(1)
  63. }
  64. if (productionBlockLooksLocal(raw)) {
  65. console.error(
  66. '\x1b[31m[release-check]\x1b[0m production 预设中仍含 127.0.0.1 / localhost,请先修正。'
  67. )
  68. process.exit(1)
  69. }
  70. if (!/https:\/\/w\.shanxiachem\.com\/api/.test(raw)) {
  71. console.error(
  72. '\x1b[31m[release-check]\x1b[0m 未在 env.js 中发现生产 API https://w.shanxiachem.com/api。'
  73. )
  74. process.exit(1)
  75. }
  76. console.warn('\x1b[32m[release-check]\x1b[0m APP_ENV=production,生产 API 配置检查通过。')
  77. }