open-dev-tools.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. /**
  6. * 打开开发者工具
  7. */
  8. function _openDevTools() {
  9. const platform = process.platform // darwin, win32, linux
  10. const { UNI_PLATFORM } = process.env // mp-weixin, mp-alipay
  11. const uniPlatformText = UNI_PLATFORM === 'mp-weixin' ? '微信小程序' : UNI_PLATFORM === 'mp-alipay' ? '支付宝小程序' : '小程序'
  12. // 项目路径(构建输出目录)
  13. const projectPath = path.resolve(process.cwd(), `dist/dev/${UNI_PLATFORM}`)
  14. // 检查构建输出目录是否存在
  15. if (!fs.existsSync(projectPath)) {
  16. console.log(`❌ ${uniPlatformText}构建目录不存在:`, projectPath)
  17. return
  18. }
  19. console.log(`🚀 正在打开${uniPlatformText}开发者工具...`)
  20. // 根据不同操作系统执行不同命令
  21. let command = ''
  22. if (platform === 'darwin') {
  23. // macOS
  24. if (UNI_PLATFORM === 'mp-weixin') {
  25. command = `/Applications/wechatwebdevtools.app/Contents/MacOS/cli -o "${projectPath}"`
  26. }
  27. else if (UNI_PLATFORM === 'mp-alipay') {
  28. command = `/Applications/小程序开发者工具.app/Contents/MacOS/小程序开发者工具 --p "${projectPath}"`
  29. }
  30. }
  31. else if (platform === 'win32' || platform === 'win64') {
  32. // Windows
  33. if (UNI_PLATFORM === 'mp-weixin') {
  34. command = `E:\developmentKit\WeChatDeveloperTools\微信web开发者工具\cli.bat -o "${projectPath}"`
  35. }
  36. }
  37. else {
  38. // Linux 或其他系统
  39. console.log('❌ 当前系统不支持自动打开微信开发者工具')
  40. return
  41. }
  42. exec(command, (error, stdout, stderr) => {
  43. if (error) {
  44. console.log(`❌ 打开${uniPlatformText}开发者工具失败:`, error.message)
  45. console.log(`💡 请确保${uniPlatformText}开发者工具服务端口已启用`)
  46. console.log(`💡 可以手动打开${uniPlatformText}开发者工具并导入项目:`, projectPath)
  47. return
  48. }
  49. if (stderr) {
  50. console.log('⚠️ 警告:', stderr)
  51. }
  52. console.log(`✅ ${uniPlatformText}开发者工具已打开`)
  53. if (stdout) {
  54. console.log(stdout)
  55. }
  56. })
  57. }
  58. export default function openDevTools() {
  59. // 首次构建标记
  60. let isFirstBuild = true
  61. return {
  62. name: 'uni-devtools',
  63. writeBundle() {
  64. if (isFirstBuild && process.env.UNI_PLATFORM?.includes('mp')) {
  65. isFirstBuild = false
  66. _openDevTools()
  67. }
  68. },
  69. }
  70. }