postupgrade.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // # 执行 `pnpm upgrade` 后会升级 `uniapp` 相关依赖
  2. // # 在升级完后,会自动添加很多无用依赖,这需要删除以减小依赖包体积
  3. // # 只需要执行下面的命令即可
  4. import { exec } from 'node:child_process'
  5. import { promisify } from 'node:util'
  6. // 日志控制开关,设置为 true 可以启用所有日志输出
  7. const FG_LOG_ENABLE = true
  8. // 将 exec 转换为返回 Promise 的函数
  9. const execPromise = promisify(exec)
  10. // 定义要执行的命令
  11. const dependencies = [
  12. // TODO: 如果不需要某个平台的小程序,请手动删除或注释掉
  13. '@dcloudio/uni-mp-baidu',
  14. '@dcloudio/uni-mp-jd',
  15. '@dcloudio/uni-mp-kuaishou',
  16. '@dcloudio/uni-mp-qq',
  17. '@dcloudio/uni-mp-xhs',
  18. '@dcloudio/uni-quickapp-webview',
  19. ]
  20. /**
  21. * 带开关的日志输出函数
  22. * @param {string} message 日志消息
  23. * @param {string} type 日志类型 (log, error)
  24. */
  25. function log(message, type = 'log') {
  26. if (FG_LOG_ENABLE) {
  27. if (type === 'error') {
  28. console.error(message)
  29. }
  30. else {
  31. console.log(message)
  32. }
  33. }
  34. }
  35. /**
  36. * 卸载单个依赖包
  37. * @param {string} dep 依赖包名
  38. * @returns {Promise<boolean>} 是否成功卸载
  39. */
  40. async function uninstallDependency(dep) {
  41. try {
  42. log(`开始卸载依赖: ${dep}`)
  43. const { stdout, stderr } = await execPromise(`pnpm un ${dep}`)
  44. if (stdout) {
  45. log(`stdout [${dep}]: ${stdout}`)
  46. }
  47. if (stderr) {
  48. log(`stderr [${dep}]: ${stderr}`, 'error')
  49. }
  50. log(`成功卸载依赖: ${dep}`)
  51. return true
  52. }
  53. catch (error) {
  54. // 单个依赖卸载失败不影响其他依赖
  55. log(`卸载依赖 ${dep} 失败: ${error.message}`, 'error')
  56. return false
  57. }
  58. }
  59. /**
  60. * 串行卸载所有依赖包
  61. */
  62. async function uninstallAllDependencies() {
  63. log(`开始串行卸载 ${dependencies.length} 个依赖包...`)
  64. let successCount = 0
  65. let failedCount = 0
  66. // 串行执行所有卸载命令
  67. for (const dep of dependencies) {
  68. const success = await uninstallDependency(dep)
  69. if (success) {
  70. successCount++
  71. }
  72. else {
  73. failedCount++
  74. }
  75. // 为了避免命令执行过快导致的问题,添加短暂延迟
  76. await new Promise(resolve => setTimeout(resolve, 100))
  77. }
  78. log(`卸载操作完成: 成功 ${successCount} 个, 失败 ${failedCount} 个`)
  79. }
  80. // 执行串行卸载
  81. uninstallAllDependencies().catch((err) => {
  82. log(`串行卸载过程中出现未捕获的错误: ${err}`, 'error')
  83. })