open-dev-tools.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { exec } from 'node:child_process'
  2. import fs from 'node:fs'
  3. import path from 'node:path'
  4. import process from 'node:process'
  5. import dotenv from 'dotenv'
  6. dotenv.config({ path: path.resolve(process.cwd(), 'env/.env') })
  7. /**
  8. * 打开开发者工具
  9. */
  10. function _openDevTools() {
  11. const platform = process.platform // darwin, win32, linux
  12. const { UNI_PLATFORM } = process.env // mp-weixin, mp-alipay
  13. const uniPlatformText = UNI_PLATFORM === 'mp-weixin' ? '微信小程序' : UNI_PLATFORM === 'mp-alipay' ? '支付宝小程序' : '小程序'
  14. // 项目路径(构建输出目录)
  15. const projectPath = path.resolve(process.cwd(), `dist/dev/${UNI_PLATFORM}`)
  16. // 检查构建输出目录是否存在
  17. if (!fs.existsSync(projectPath)) {
  18. console.log(`❌ ${uniPlatformText}构建目录不存在:`, projectPath)
  19. return
  20. }
  21. console.log(`🚀 正在打开${uniPlatformText}开发者工具...`)
  22. // 根据不同操作系统执行不同命令
  23. let command = ''
  24. if (platform === 'darwin') {
  25. // macOS
  26. if (UNI_PLATFORM === 'mp-weixin') {
  27. command = `/Applications/wechatwebdevtools.app/Contents/MacOS/cli -o --project "${projectPath}"`
  28. }
  29. else if (UNI_PLATFORM === 'mp-alipay') {
  30. command = `/Applications/小程序开发者工具.app/Contents/MacOS/小程序开发者工具 --p "${projectPath}"`
  31. }
  32. }
  33. else if (platform === 'win32' || platform === 'win64') {
  34. // Windows
  35. if (UNI_PLATFORM === 'mp-weixin') {
  36. // 获取微信开发者工具路径,添加默认值或错误处理
  37. const wechatDevToolPath = process.env.VITE_WECHAT_DEV_TOOL_PROJECT_PATH || 'C:\\Program Files (x86)\\Tencent\\微信web开发者工具'
  38. if (!wechatDevToolPath) {
  39. console.log('❌ 未配置微信开发者工具路径,请在 .env 文件中设置 VITE_WECHAT_DEV_TOOL_PROJECT_PATH')
  40. return
  41. }
  42. const cliPath = path.join(wechatDevToolPath, 'cli.bat')
  43. command = `${cliPath} open --project "${projectPath}"`
  44. }
  45. }
  46. else {
  47. // Linux 或其他系统
  48. console.log('❌ 当前系统不支持自动打开微信开发者工具')
  49. return
  50. }
  51. exec(command, (error, stdout, stderr) => {
  52. if (error) {
  53. console.log(`❌ 打开${uniPlatformText}开发者工具失败:`, error.message)
  54. console.log(`💡 请确保${uniPlatformText}开发者工具服务端口已启用`)
  55. console.log(`💡 可以手动打开${uniPlatformText}开发者工具并导入项目:`, projectPath)
  56. return
  57. }
  58. if (stderr) {
  59. console.log('⚠️ 警告:', stderr)
  60. }
  61. console.log(`✅ ${uniPlatformText}开发者工具已打开`)
  62. if (stdout) {
  63. console.log(stdout)
  64. }
  65. })
  66. }
  67. export default function openDevTools() {
  68. // 首次构建标记
  69. let isFirstBuild = true
  70. return {
  71. name: 'uni-devtools',
  72. writeBundle() {
  73. if (isFirstBuild && process.env.UNI_PLATFORM?.includes('mp')) {
  74. isFirstBuild = false
  75. _openDevTools()
  76. }
  77. },
  78. }
  79. }