diff --git a/README.md b/README.md index b492324..2419cfa 100644 --- a/README.md +++ b/README.md @@ -118,9 +118,9 @@ - 注入方式:编译期命令行环境变量 `VUE_APP_API_BASE_OVERRIDE`(**不写入任何 .env 文件、不落盘**),在 `src/env.js` 中优先级最高。与工作台项目的 `VITE_API_BASE_OVERRIDE` 是同一套思路。 - 测试包产物单独放 `release/android/dev/` 且文件名带 `_dev`,**不会覆盖发行包**,也不会触发发布上传(自动加 `-Dev -NoUpload`)。 - 两道校验方向相反:发行包**反向**校验(产物中不得出现 `192.168.x.x`/`127.0.0.1`);测试包**正向**校验(产物中必须出现注入的地址,否则中止,避免装成生产包却以为在测开发环境)。 -- 真机 JS 日志(release 包里 console 走这两个 tag): +- 真机 JS 日志:**离线 release 包默认不会把 `console.log` 输出到 logcat**(HBuilderX「运行到手机」靠的是 debug 基座)。测试包由 `src/core/utils/dev-log.js` 用 `plus.android` 桥接 `android.util.Log`,把 console 转发到 logcat 的 `jsLog` tag(`dev:adb` 会自动注入开关并实时跟随打印): ```powershell - & "$env:ANDROID_HOME\platform-tools\adb.exe" -s <序列号> logcat UniConsole:V UniViewConsole:V *:S + & "$env:ANDROID_HOME\platform-tools\adb.exe" -s <序列号> logcat jsLog:V UniConsole:V UniViewConsole:V *:S ``` ### App 端调试与打包 diff --git a/scripts/dev-adb.cjs b/scripts/dev-adb.cjs index e36798e..e9b3491 100644 --- a/scripts/dev-adb.cjs +++ b/scripts/dev-adb.cjs @@ -1,23 +1,28 @@ /** - * 真机调试包(测试模式):编译时注入指定接口地址 → 打包 → 安装到设备 → 启动。 + * 真机调试(测试模式):注入接口地址 → 编译 → 打包 → 装机 → 启动 → 跟随日志 → 监听改动自动重来。 * * 与 `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,绝不覆盖发行包。 + * - 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 # 默认注入 .env.development.local 的地址 + * 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-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 { spawnSync } = require('child_process') +const { spawn, spawnSync } = require('child_process') const fs = require('fs') const path = require('path') @@ -25,9 +30,7 @@ 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 LAUNCH_COMPONENT = `${PACKAGE_NAME}/io.dcloud.PandoraEntry` -const log = (msg) => console.log(`[dev:adb] ${msg}`) const argv = process.argv.slice(2) const hasFlag = (name) => argv.includes(name) const argValue = (name) => { @@ -35,6 +38,13 @@ const argValue = (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 = [] @@ -73,6 +83,13 @@ function resolveApiTarget() { 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, { @@ -98,6 +115,16 @@ function collectFiles(dir, out = []) { 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' }) @@ -110,7 +137,7 @@ function listDevices() { } function pickDevice() { - const wanted = argValue('--serial') || argValue('-s') + const wanted = argValue('--serial') const devices = listDevices() if (!devices.length) { console.error('[dev:adb] 未检测到已连接设备(USB 未插好、未授权,或无线调试未 adb connect)') @@ -129,77 +156,202 @@ function pickDevice() { devices.forEach((d) => console.error(` ${d.serial} ${d.desc}`)) process.exit(1) } - log(`目标设备: ${devices[0].serial} ${devices[0].desc}`) return devices[0] } -// ---------- 主流程 ---------- -const apiTarget = resolveApiTarget() -const device = pickDevice() +// ---------- 真机日志跟随 ---------- +let logcatProc = null +let shuttingDown = false -log(`接口地址 = ${apiTarget.base || 'src/env.js 的 PROD_API_BASE(生产)'} 〔${apiTarget.note}〕`) - -// 1. 编译(生产模式编译,但注入 override 指向测试环境) -log('step 1/4: 编译 App 资源 ...') -const buildEnv = apiTarget.base ? { VUE_APP_API_BASE_OVERRIDE: apiTarget.base } : {} -if (!run('npm', ['run', 'build:app-plus:dev'], buildEnv)) { - console.error('[dev:adb] ✗ 编译失败') - process.exit(1) +function clearLogcat(serial) { + spawnSync(ADB, ['-s', serial, 'logcat', '-c'], { stdio: 'ignore' }) } -// 2. 校验注入结果(正向校验:期望地址必须出现在产物里) -log('step 2/4: 校验接口地址注入 ...') -const files = collectFiles(APP_BUILD_DIR) -if (!files.length) { - console.error(`[dev:adb] ✗ 未找到构建产物: ${APP_BUILD_DIR}`) - process.exit(1) +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)') } -if (apiTarget.base) { - const host = apiTarget.base.replace(/^https?:\/\//, '').replace(/\/.*$/, '') - const hit = files.find((f) => fs.readFileSync(f, 'utf-8').includes(host)) - if (!hit) { - console.error(`[dev:adb] ✗ 产物中未找到注入的地址 ${apiTarget.base},注入可能未生效,已中止`) - console.error(' 排查:src/env.js 是否仍以 VUE_APP_API_BASE_OVERRIDE 为最高优先级') - process.exit(1) + +process.on('SIGINT', () => { + shuttingDown = true + if (logcatProc) { + logcatProc.kill() + logcatProc = null } - log(`✓ 已确认产物使用 ${apiTarget.base}`) -} else { - if (!run('node', ['scripts/check-build-env.cjs', 'dist/build/app-plus'])) { - console.error('[dev:adb] ✗ 产物地址校验未通过') - process.exit(1) - } -} - -// 3. 打包(-Dev:产物进 release/android/dev 且带 _dev 后缀,不触发发布上传) -log('step 3/4: 离线打包 ...') -if (!run('npm', ['run', 'android:pack:raw', '--', '-Dev', '-NoUpload'])) { - console.error('[dev:adb] ✗ 打包失败') - process.exit(1) -} -const apks = fs.existsSync(DEV_APK_DIR) - ? fs.readdirSync(DEV_APK_DIR).filter((f) => f.endsWith('.apk')).map((f) => ({ f, t: fs.statSync(path.join(DEV_APK_DIR, f)).mtimeMs })) - : [] -apks.sort((a, b) => b.t - a.t) -if (!apks.length) { - console.error(`[dev:adb] ✗ 未找到 APK: ${DEV_APK_DIR}`) - process.exit(1) -} -const apkPath = path.join(DEV_APK_DIR, apks[0].f) -log(`✓ 测试包: ${path.relative(ROOT, apkPath)}`) - -if (hasFlag('--no-install')) { - log('--no-install 指定,结束(未安装)') + 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 } -// 4. 安装 + 启动 -log('step 4/4: 安装并启动 ...') -if (!run(ADB, ['-s', device.serial, 'install', '-r', apkPath])) { - console.error('[dev:adb] ✗ 安装失败') - process.exit(1) +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') + } + } } -if (!hasFlag('--no-launch')) { - run(ADB, ['-s', device.serial, 'shell', 'am', 'start', '-n', LAUNCH_COMPONENT]) + +// ---------- 目录监听 ---------- +// 监听范围: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 退出)') } -log('完成。查看应用日志(release 包里 JS console 走 UniConsole/UniViewConsole 两个 tag):') -log(` & "$env:ANDROID_HOME\\platform-tools\\adb.exe" -s ${device.serial} logcat UniConsole:V UniViewConsole:V *:S`) + +// ---------- 主流程 ---------- +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`) diff --git a/src/core/utils/dev-log.js b/src/core/utils/dev-log.js new file mode 100644 index 0000000..15ca220 --- /dev/null +++ b/src/core/utils/dev-log.js @@ -0,0 +1,79 @@ +/** + * 测试包专用:把 JS 的 console 输出转发到 Android logcat(tag: jsLog), + * 这样 `npm run dev:adb` 就能把真机 console 实时打到控制台(见 scripts/dev-adb.cjs)。 + * + * 背景:uni-app 的 release / 离线打包产物默认**不会**把 JS console 输出到 logcat + * (HBuilderX「运行到手机」用的是 debug 基座才有这个能力,其运行时类 + * io.dcloud.weex.ConsoleLogUtils 也是用 jsLog 这个 tag 转发 __LOG/__WARN 等前缀)。 + * 因此测试包自己用 plus.android 调 android.util.Log 落日志。 + * + * 生效条件:构建时注入 VUE_APP_JS_LOG_TO_LOGCAT=1(仅 dev-adb 注入)。 + * 发行包里该判断是常量,整个分支会被 webpack 折叠掉,不产生运行时开销,也不会打日志。 + */ +export function setupDevLogToLogcat () { + // #ifdef APP-PLUS + if (process.env.VUE_APP_JS_LOG_TO_LOGCAT !== '1') { + return + } + + const LOG_TAG = 'jsLog' + + const stringify = (args) => { + const parts = [] + for (const arg of args) { + if (typeof arg === 'string') { + parts.push(arg) + } else { + try { + parts.push(JSON.stringify(arg)) + } catch (e) { + parts.push(String(arg)) + } + } + } + return parts.join(' ') + } + + const install = () => { + const androidLog = plus.android.importClass('android.util.Log') + const wrapped = [['log', 'd'], ['info', 'i'], ['warn', 'w'], ['error', 'e']] + for (const [name, level] of wrapped) { + const origin = console[name] ? console[name].bind(console) : () => {} + console[name] = (...args) => { + origin(...args) + try { + androidLog[level](LOG_TAG, stringify(args)) + } catch (e) { + // 单条日志失败不影响业务 + } + } + } + console.log('[dev-log] JS 日志已转发到 logcat(tag=jsLog),仅测试包生效') + } + + if (typeof plus !== 'undefined' && plus.android) { + try { + install() + } catch (e) { + console.warn('[dev-log] 初始化失败:', e && e.message) + } + return + } + + // plus 尚未就绪时兜底重试(正常不会走到) + let attempts = 0 + const timer = setInterval(() => { + attempts += 1 + if (typeof plus !== 'undefined' && plus.android) { + clearInterval(timer) + try { + install() + } catch (e) { + console.warn('[dev-log] 初始化失败:', e && e.message) + } + } else if (attempts >= 25) { + clearInterval(timer) + } + }, 200) + // #endif +} diff --git a/src/main.js b/src/main.js index b0bf1ae..1f74b18 100644 --- a/src/main.js +++ b/src/main.js @@ -11,6 +11,10 @@ import { RouterMount } from "@/core/router"; import store from "@/core/store"; +import { setupDevLogToLogcat } from "@/core/utils/dev-log"; + +// 仅测试包(npm run dev:adb)生效:把 console 输出转发到 logcat,便于真机日志实时查看 +setupDevLogToLogcat(); Vue.config.productionTip = false App.mpType = 'app'