/** * 真机调试(测试模式):注入接口地址 → 编译 → 打包 → 装机 → 启动 → 跟随日志 → 监听改动自动重来。 * * 与 `npm run build:apk` 的区别: * - build:apk → 发行包。接口地址固定为 src/env.js 的 PROD_API_BASE,构建后强制校验产物不含内网地址。 * - dev:adb → 测试包。接口地址在编译期由本脚本注入(默认取 .env.development.local 的 * VUE_APP_API_BASE_URL),产物进 release/android/dev/*_dev.apk,绝不覆盖发行包。 * * 注入方式(与工作台 wms_worker_station 一致):命令行环境变量 VUE_APP_API_BASE_OVERRIDE, * 不写入任何 .env 文件、不落盘;在 src/env.js 中优先级高于生产常量,详见该文件顶部说明。 * * 用法: * npm run dev:adb # 默认:构建→装机→启动→跟随真机日志→监听改动自动重来 * npm run dev:adb -- --once # 只跑一遍(CI/脚本调用用,不监听) * npm run dev:adb -- --prod-api # 不注入,产出与发行包一致的包(排查线上问题时用) * npm run dev:adb -- --api=http://192.168.1.10:6060 * npm run dev:adb -- --no-install # 只编译 + 打包 * npm run dev:adb -- --no-launch # 装机后不自动启动 * npm run dev:adb -- --no-logcat # 不跟随真机日志 * npm run dev:adb -- --serial=4235737 # 多设备时指定目标设备 * * 真机日志:release 包里 JS 的 console 走 UniConsole(逻辑层) / UniViewConsole(视图层) 两个 tag, * 本脚本默认跟随这两个 tag 实时打印到控制台(出错行标红)。 */ const { spawn, spawnSync } = require('child_process') const fs = require('fs') const path = require('path') const ROOT = path.resolve(__dirname, '..') const APP_BUILD_DIR = path.join(ROOT, 'dist', 'build', 'app-plus') const DEV_APK_DIR = path.join(ROOT, 'release', 'android', 'dev') const PACKAGE_NAME = 'com.gztbyc.pda_wms' const argv = process.argv.slice(2) const hasFlag = (name) => argv.includes(name) const argValue = (name) => { const hit = argv.find((a) => a.startsWith(`${name}=`)) return hit ? hit.slice(name.length + 1) : '' } const ONCE = hasFlag('--once') || hasFlag('--no-watch') const NO_INSTALL = hasFlag('--no-install') const NO_LAUNCH = hasFlag('--no-launch') const NO_LOGCAT = hasFlag('--no-logcat') const log = (msg) => console.log(`[dev:adb] ${msg}`) // ---------- adb 探测 ---------- function detectAdb() { const candidates = [] const home = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || '' if (home) candidates.push(path.join(home, 'platform-tools', process.platform === 'win32' ? 'adb.exe' : 'adb')) if (process.env.LOCALAPPDATA) candidates.push(path.join(process.env.LOCALAPPDATA, 'Android', 'Sdk', 'platform-tools', 'adb.exe')) candidates.push(process.platform === 'win32' ? 'adb.exe' : 'adb') for (const c of candidates) { const res = spawnSync(c, ['version'], { encoding: 'utf-8' }) if (res.status === 0 && /Android Debug Bridge/.test(res.stdout || '')) return c } return 'adb' } const ADB = detectAdb() // ---------- 接口地址解析 ---------- function readEnvValue(file, key) { try { const text = fs.readFileSync(path.join(ROOT, file), 'utf-8') for (const line of text.split(/\r?\n/)) { const m = line.match(/^\s*([A-Za-z0-9_]+)\s*=\s*(.*)$/) if (m && m[1] === key) return m[2].trim().replace(/^["']|["']$/g, '') } } catch (e) { // 文件不存在视为未配置 } return '' } function resolveApiTarget() { if (hasFlag('--prod-api')) return { base: '', note: '--prod-api 指定,与发行包一致(生产地址)' } const argApi = argValue('--api') if (argApi) return { base: argApi, note: '命令行 --api 指定' } const fromEnv = readEnvValue('.env.development.local', 'VUE_APP_API_BASE_URL') || readEnvValue('.env.local', 'VUE_APP_API_BASE_URL') if (fromEnv) return { base: fromEnv, note: '.env.development.local 的 VUE_APP_API_BASE_URL' } return { base: '', note: '未配置开发地址,沿用构建默认(生产地址)' } } const API_TARGET = resolveApiTarget() const BUILD_ENV = { ...(API_TARGET.base ? { VUE_APP_API_BASE_OVERRIDE: API_TARGET.base } : {}), // 测试包始终开启 JS→logcat 转发(发行包不注入该变量,见 src/core/utils/dev-log.js) VUE_APP_JS_LOG_TO_LOGCAT: '1', } // ---------- 工具 ---------- function run(cmd, args, env) { const res = spawnSync(cmd, args, { cwd: ROOT, stdio: 'inherit', env: { ...process.env, ...(env || {}) }, shell: process.platform === 'win32', }) if (res.error) { console.error(`[dev:adb] 执行失败 ${cmd}: ${res.error.message}`) return false } return res.status === 0 } function collectFiles(dir, out = []) { if (!fs.existsSync(dir)) return out for (const name of fs.readdirSync(dir)) { const full = path.join(dir, name) if (fs.statSync(full).isDirectory()) collectFiles(full, out) else if (/\.(js|html|json)$/i.test(name)) out.push(full) } return out } function findDevApk() { if (!fs.existsSync(DEV_APK_DIR)) return null const apks = fs.readdirSync(DEV_APK_DIR) .filter((f) => f.endsWith('.apk')) .map((f) => ({ name: f, mtime: fs.statSync(path.join(DEV_APK_DIR, f)).mtimeMs })) if (!apks.length) return null apks.sort((a, b) => b.mtime - a.mtime) return path.join(DEV_APK_DIR, apks[0].name) } // ---------- 设备 ---------- function listDevices() { const res = spawnSync(ADB, ['devices', '-l'], { encoding: 'utf-8' }) const devices = [] for (const line of (res.stdout || '').split(/\r?\n/)) { const m = line.trim().match(/^(\S+)\s+device\b(.*)$/) if (m) devices.push({ serial: m[1], desc: m[2].trim() }) } return devices } function pickDevice() { const wanted = argValue('--serial') const devices = listDevices() if (!devices.length) { console.error('[dev:adb] 未检测到已连接设备(USB 未插好、未授权,或无线调试未 adb connect)') process.exit(1) } if (wanted) { const hit = devices.find((d) => d.serial === wanted) if (!hit) { console.error(`[dev:adb] 未找到设备 ${wanted},当前:${devices.map((d) => d.serial).join(', ')}`) process.exit(1) } return hit } if (devices.length > 1) { console.error('[dev:adb] 检测到多台设备,请用 --serial=<序列号> 指定:') devices.forEach((d) => console.error(` ${d.serial} ${d.desc}`)) process.exit(1) } return devices[0] } // ---------- 真机日志跟随 ---------- let logcatProc = null let shuttingDown = false function clearLogcat(serial) { spawnSync(ADB, ['-s', serial, 'logcat', '-c'], { stdio: 'ignore' }) } function startLogcat(serial) { if (NO_LOGCAT || logcatProc || shuttingDown) return clearLogcat(serial) logcatProc = spawn(ADB, ['-s', serial, 'logcat', '-v', 'time', 'jsLog:V', 'UniConsole:V', 'UniViewConsole:V', '*:S'], { stdio: ['ignore', 'pipe', 'inherit'], }) let buf = '' logcatProc.stdout.setEncoding('utf-8') logcatProc.stdout.on('data', (chunk) => { buf += chunk let idx while ((idx = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, idx).trim() buf = buf.slice(idx + 1) if (!line) continue const isErr = / W\/| E\//.test(line) console.log(isErr ? `\x1b[31m[真机] ${line}\x1b[0m` : `\x1b[36m[真机] ${line}\x1b[0m`) } }) logcatProc.on('exit', () => { logcatProc = null if (!shuttingDown) { // adb 重连/设备重启后自动恢复跟随 setTimeout(() => startLogcat(serial), 3000) } }) log('真机 console 实时打印已开启(jsLog / UniConsole / UniViewConsole)') } process.on('SIGINT', () => { shuttingDown = true if (logcatProc) { logcatProc.kill() logcatProc = null } log('已退出监听的日志跟随') process.exit(0) }) // ---------- 构建 → 安装 → 启动 ---------- async function buildAndInstall(device, trigger) { const serial = device.serial const t0 = Date.now() log(`开始构建(触发: ${trigger})`) log(`接口地址 = ${API_TARGET.base || 'src/env.js 的 PROD_API_BASE(生产)'} 〔${API_TARGET.note}〕`) // 1. 编译 App 资源(生产模式编译,但注入 override 指向测试环境) if (!run('npm', ['run', 'build:app-plus:dev'], BUILD_ENV)) { log('✗ 编译失败,跳过安装') return false } // 2. 校验注入结果(正向:期望地址必须出现在产物里) const files = collectFiles(APP_BUILD_DIR) if (!files.length) { log(`✗ 未找到构建产物: ${path.relative(ROOT, APP_BUILD_DIR)}`) return false } if (API_TARGET.base) { const host = API_TARGET.base.replace(/^https?:\/\//, '').replace(/\/.*$/, '') const hit = files.find((f) => fs.readFileSync(f, 'utf-8').includes(host)) if (!hit) { log(`✗ 产物中未找到注入的地址 ${API_TARGET.base},注入可能未生效,已中止`) return false } log(`✓ 已确认产物使用 ${API_TARGET.base}`) } else if (!run('node', ['scripts/check-build-env.cjs', 'dist/build/app-plus'])) { log('✗ 产物地址校验未通过') return false } // 3. 离线打包(-Dev:产物进 release/android/dev 且带 _dev 后缀,不触发发布上传) if (!run('npm', ['run', 'android:pack:raw', '--', '-Dev', '-NoUpload'])) { log('✗ 打包失败,跳过安装') return false } const apk = findDevApk() if (!apk) { log(`✗ 未找到 APK: ${path.relative(ROOT, DEV_APK_DIR)}`) return false } log(`APK: ${path.relative(ROOT, apk)}`) if (NO_INSTALL) { log(`✓ 编译 + 打包完成,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s(--no-install 未安装)`) return true } // 4. 安装(设备忙时常见失败,重试 3 次) for (let i = 0; i < 3; i++) { if (spawnSync(ADB, ['-s', serial, 'install', '-r', apk], { stdio: 'inherit' }).status === 0) break if (i === 2) { log('✗ adb install 失败(已重试 3 次)') return false } log(`安装失败,2 秒后重试 (${i + 1}/2)`) await new Promise((r) => setTimeout(r, 2000)) } // 5. 启动(先停进程,再用 monkey 拉起 launcher 入口最稳) if (!NO_LAUNCH) { if (!NO_LOGCAT) startLogcat(serial) else clearLogcat(serial) spawnSync(ADB, ['-s', serial, 'shell', 'am', 'force-stop', PACKAGE_NAME], { stdio: 'ignore' }) spawnSync(ADB, ['-s', serial, 'shell', 'monkey', '-p', PACKAGE_NAME, '-c', 'android.intent.category.LAUNCHER', '1'], { stdio: 'ignore' }) log('已启动应用') } log(`✓ 完成,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s`) return true } let building = false let pending = false async function triggerBuild(device, trigger) { if (building) { pending = true return } building = true try { await buildAndInstall(device, trigger) } finally { building = false if (pending) { pending = false log('构建期间有新变更,继续构建...') triggerBuild(device, 'pending') } } } // ---------- 目录监听 ---------- // 监听范围:src/(uni-app 前端)、原生 java、以及 src/main 直接子文件(AndroidManifest.xml)。 // 注意:不监听 src/main/assets(prepare 注入产物)与 res(图标/启动图覆盖产物),否则构建会自触发死循环。 const WATCH_ROOTS = [ { dir: path.join(ROOT, 'src'), recursive: true }, { dir: path.join(ROOT, 'android-offline', 'HBuilder-Integrate-AS', 'simpleDemo', 'src', 'main', 'java'), recursive: true }, { dir: path.join(ROOT, 'android-offline', 'HBuilder-Integrate-AS', 'simpleDemo', 'src', 'main'), recursive: false }, ] const WATCH_EXTS = new Set(['.vue', '.js', '.ts', '.json', '.scss', '.css', '.cjs', '.ps1', '.xml', '.java', '.png', '.jpg', '.jpeg']) const IGNORE_SEGMENTS = [`${path.sep}assets${path.sep}`, `${path.sep}unpackage${path.sep}`, `${path.sep}dist${path.sep}`, `${path.sep}node_modules${path.sep}`] function startWatch(device) { let timer = null for (const root of WATCH_ROOTS) { if (!fs.existsSync(root.dir)) { log(`警告: 监听目录不存在: ${path.relative(ROOT, root.dir)}`) continue } try { fs.watch(root.dir, { recursive: root.recursive }, (event, filename) => { const rel = filename ? path.join(root.dir, filename) : root.dir if (IGNORE_SEGMENTS.some((seg) => rel.includes(seg))) return if (filename && !WATCH_EXTS.has(path.extname(filename).toLowerCase())) return if (timer) clearTimeout(timer) timer = setTimeout(() => { timer = null triggerBuild(device, path.relative(ROOT, rel)) }, 800) }) log(`监听中: ${path.relative(ROOT, root.dir)}${root.recursive ? '' : '(不递归)'}`) } catch (e) { log(`警告: 无法监听 ${root.dir}: ${e.message}`) } } log('改动文件即自动重编重装(Ctrl+C 退出)') } // ---------- 主流程 ---------- const device = pickDevice() log(`目标设备: ${device.serial} ${device.desc}`) triggerBuild(device, '首次').then(() => { if (ONCE) { if (NO_LOGCAT || NO_LAUNCH) { log('--once 指定,不进入监听,结束') } else { log('--once 指定:不监听文件改动,但继续跟随真机日志(Ctrl+C 退出)') } return } startWatch(device) }) log(`单独查看真机日志:adb -s ${device.serial} logcat jsLog:V UniConsole:V UniViewConsole:V *:S`)