From 582fc47f4bff65b1332c52fc0e6a2aa832a26f82 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Mon, 9 Nov 2026 15:04:55 -0800 Subject: [PATCH] feat: debug Vite projects with HMR when @nativescript/vite serves source maps @nativescript/vite 8.0.23 serves HMR app modules with inline source maps, so breakpoints bind without restarting the app on every change. Only add --no-hmr for older versions (or when the version can't be read) and for Vue projects, whose single-file components are still served without maps. --- README.md | 2 +- src/project/projectInfo.ts | 32 +++++++++++++++++---- src/services/buildService.ts | 28 ++++++++++++++++-- src/tests/buildService.test.ts | 35 +++++++++++++++++++++-- src/tests/projectInfo.test.ts | 52 +++++++++++++++++++++++++++++++++- 5 files changed, 137 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d89282d..91e7b90 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ If your project is started through another tool, set `runtimeExecutable` and `ru #### Vite projects -Projects using the Vite bundler (`bundler: 'vite'` in `nativescript.config.ts`) are debugged with `--no-hmr`, because hot module replacement serves app code without source maps. File changes still rebuild and restart the app, and the debugger reattaches. Pass `--hmr` in `tnsArgs` to keep HMR on (breakpoints in app code won't bind). Debugging unit tests that use the Vitest runner is not supported yet. +Projects using the Vite bundler (`bundler: 'vite'` in `nativescript.config.ts`) are debugged with hot module replacement when `@nativescript/vite` is 8.0.23 or later, which serves app modules with source maps. Breakpoints stay bound as you edit, because HMR updates replace modules in the running app without restarting it. With older versions, and for Vue projects (whose `.vue` components are still served without source maps), the extension adds `--no-hmr`. File changes then rebuild and restart the app, and the debugger reattaches. An explicit `--hmr` or `--no-hmr` in `tnsArgs` is always used as given. Debugging unit tests that use the Vitest runner is not supported yet. ### NativeScript commands diff --git a/src/project/projectInfo.ts b/src/project/projectInfo.ts index c757705..7b668fb 100644 --- a/src/project/projectInfo.ts +++ b/src/project/projectInfo.ts @@ -37,6 +37,14 @@ export function readPackageJson(appRoot: string): { name?: string; [key: string] } } +export function hasDependency(appRoot: string, packageName: string): boolean { + const packageJson = readPackageJson(appRoot); + return ['dependencies', 'devDependencies'].some((field) => { + const deps = packageJson?.[field]; + return typeof deps === 'object' && deps !== null && packageName in deps; + }); +} + /** Mirrors the CLI's ProjectData.getAppDirectoryRelativePath. */ export function getAppDirectory(appRoot: string): string { const legacyConfig = readFile(path.join(appRoot, 'nsconfig.json')); @@ -58,15 +66,14 @@ export function getBundler(appRoot: string): Bundler { } /** - * Finds a locally installed CLI (`node_modules/.bin/ns`) in appRoot or any parent directory, like npx does, so - * monorepos that install it at the workspace root are covered. + * Finds `node_modules/` in appRoot or any parent directory, like Node resolution and npx do, so + * monorepos that install packages at the workspace root are covered. */ -export function findLocalCli(appRoot: string, platform: NodeJS.Platform = process.platform): string | undefined { - const binName = platform === 'win32' ? 'ns.cmd' : 'ns'; +function findInNodeModules(appRoot: string, relativePath: string): string | undefined { let dir = path.resolve(appRoot); while (true) { - const candidate = path.join(dir, 'node_modules', '.bin', binName); + const candidate = path.join(dir, 'node_modules', relativePath); if (fs.existsSync(candidate)) return candidate; const parent = path.dirname(dir); @@ -75,6 +82,21 @@ export function findLocalCli(appRoot: string, platform: NodeJS.Platform = proces } } +export function findLocalCli(appRoot: string, platform: NodeJS.Platform = process.platform): string | undefined { + return findInNodeModules(appRoot, path.join('.bin', platform === 'win32' ? 'ns.cmd' : 'ns')); +} + +export function getInstalledPackageVersion(appRoot: string, packageName: string): string | undefined { + const packageJson = findInNodeModules(appRoot, path.join(packageName, 'package.json')); + if (!packageJson) return undefined; + try { + const version = (JSON.parse(fs.readFileSync(packageJson, 'utf8')) as { version?: unknown }).version; + return typeof version === 'string' ? version : undefined; + } catch { + return undefined; + } +} + export function isVitestProject(appRoot: string): boolean { return ['ts', 'mts', 'js', 'mjs'].some((ext) => fs.existsSync(path.join(appRoot, `vitest.config.${ext}`))); } diff --git a/src/services/buildService.ts b/src/services/buildService.ts index f17a8af..3341b78 100644 --- a/src/services/buildService.ts +++ b/src/services/buildService.ts @@ -1,10 +1,11 @@ import * as fs from 'fs'; import * as path from 'path'; +import * as semver from 'semver'; import { ChildProcess } from 'child_process'; import { EventEmitter } from 'events'; import { ILogger } from '../common/logger'; import * as utils from '../common/utilities'; -import { getBundler, isVitestProject } from '../project/projectInfo'; +import { getBundler, getInstalledPackageVersion, hasDependency, isVitestProject } from '../project/projectInfo'; import { AndroidProject } from '../project/androidProject'; import { IosProject } from '../project/iosProject'; import { NativeScriptCli } from '../project/nativeScriptCli'; @@ -31,6 +32,9 @@ export interface BuildArgs { /** Ignore repeated port announcements closer together than this; the CLI can print the same port twice. */ const DUPLICATE_PORT_WINDOW_MS = 2000; +/** First @nativescript/vite release whose HMR server attaches source maps to the app modules it serves. */ +export const VITE_HMR_SOURCE_MAPS_VERSION = '8.0.23'; + /** How long the CLI gets to clean up after SIGINT before it is killed. */ export const CLI_EXIT_TIMEOUT_MS = 5000; @@ -168,8 +172,11 @@ export class BuildService { let tnsArgs = [...(args.tnsArgs ?? [])]; if (getBundler(args.appRoot) === 'vite' && !tnsArgs.some((arg) => /^--(no-)?hmr$/.test(arg))) { - // Vite HMR serves app code over HTTP without source maps, so breakpoints can't bind. - tnsArgs.push('--no-hmr'); + const reason = this.getHmrDebuggingBlocker(args.appRoot); + if (reason) { + this.logger.log(`[NativeScript] ${reason}, so debugging with --no-hmr.\n`); + tnsArgs.push('--no-hmr'); + } } if (args.request === 'launch' && platform === 'ios' && !this.getTeamId(args.appRoot, tnsArgs)) { @@ -227,6 +234,21 @@ export class BuildService { return new BuildSession(project.monitor(child, runtimeArgs), this.logger); } + /** Why breakpoints in app code could not bind under Vite HMR, or undefined when they can. */ + private getHmrDebuggingBlocker(appRoot: string): string | undefined { + const viteVersion = getInstalledPackageVersion(appRoot, '@nativescript/vite'); + if ( + !viteVersion || + !semver.satisfies(viteVersion, `>=${VITE_HMR_SOURCE_MAPS_VERSION}`, { includePrerelease: true }) + ) { + return `@nativescript/vite ${viteVersion ?? '(not found)'} serves HMR modules without source maps (fixed in ${VITE_HMR_SOURCE_MAPS_VERSION})`; + } + if (hasDependency(appRoot, 'nativescript-vue')) { + return 'Vue single-file components are served without source maps under HMR'; + } + return undefined; + } + private createProject(platform: string, appRoot: string, cli: NativeScriptCli, options: ProjectOptions): Project { return platform === 'ios' ? new IosProject(appRoot, cli, options) : new AndroidProject(appRoot, cli, options); } diff --git a/src/tests/buildService.test.ts b/src/tests/buildService.test.ts index 114cb3a..6474ad0 100644 --- a/src/tests/buildService.test.ts +++ b/src/tests/buildService.test.ts @@ -10,7 +10,13 @@ import { AnalyticsService } from '../analytics/analyticsService'; import * as utils from '../common/utilities'; import { NativeScriptCli } from '../project/nativeScriptCli'; import { IDebugResult, ProjectOptions } from '../project/project'; -import { BuildArgs, BuildService, BuildSession, CLI_EXIT_TIMEOUT_MS } from '../services/buildService'; +import { + BuildArgs, + BuildService, + BuildSession, + CLI_EXIT_TIMEOUT_MS, + VITE_HMR_SOURCE_MAPS_VERSION, +} from '../services/buildService'; import { services } from '../services/extensionHostServices'; import { iOSTeamService } from '../services/iOSTeamService'; @@ -347,11 +353,36 @@ describe('BuildService.startBuild', () => { }); describe('Vite projects', () => { + const installVite = (version: string) => + writeAppFile('node_modules/@nativescript/vite/package.json', JSON.stringify({ version })); + beforeEach(() => { writeAppFile('nativescript.config.ts', "export default { id: 'org.demo', bundler: 'vite' };\n"); }); - it('appends --no-hmr', async () => { + it.each(['8.0.22', '8.0.23-alpha.0'])('appends --no-hmr for @nativescript/vite %s', async (version) => { + installVite(version); + await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] })); + expect(debugTnsArgs()).toEqual(['--env.foo', '--no-hmr']); + }); + + it('appends --no-hmr when the @nativescript/vite version is unknown', async () => { + await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] })); + expect(debugTnsArgs()).toEqual(['--env.foo', '--no-hmr']); + }); + + it.each([VITE_HMR_SOURCE_MAPS_VERSION, '8.1.0-alpha.0', '9.0.0'])( + 'keeps HMR for @nativescript/vite %s', + async (version) => { + installVite(version); + await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] })); + expect(debugTnsArgs()).toEqual(['--env.foo']); + }, + ); + + it('appends --no-hmr for Vue projects, whose single-file components have no HMR source maps', async () => { + installVite(VITE_HMR_SOURCE_MAPS_VERSION); + writeAppFile('package.json', JSON.stringify({ dependencies: { 'nativescript-vue': '^3.1.1' } })); await service.startBuild(baseArgs({ tnsArgs: ['--env.foo'] })); expect(debugTnsArgs()).toEqual(['--env.foo', '--no-hmr']); }); diff --git a/src/tests/projectInfo.test.ts b/src/tests/projectInfo.test.ts index 94607bc..9286e62 100644 --- a/src/tests/projectInfo.test.ts +++ b/src/tests/projectInfo.test.ts @@ -2,7 +2,15 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { findLocalCli, getAppDirectory, getBundler, isVitestProject, readPackageJson } from '../project/projectInfo'; +import { + findLocalCli, + getAppDirectory, + getBundler, + getInstalledPackageVersion, + hasDependency, + isVitestProject, + readPackageJson, +} from '../project/projectInfo'; describe('projectInfo', () => { let appRoot: string; @@ -101,6 +109,48 @@ describe('projectInfo', () => { }); }); + describe('hasDependency', () => { + it('finds runtime and dev dependencies', () => { + writeAppFile('package.json', JSON.stringify({ dependencies: { a: '1' }, devDependencies: { b: '1' } })); + + expect(hasDependency(appRoot, 'a')).toBe(true); + expect(hasDependency(appRoot, 'b')).toBe(true); + expect(hasDependency(appRoot, 'c')).toBe(false); + }); + + it('is false without a package.json', () => { + expect(hasDependency(appRoot, 'a')).toBe(false); + }); + }); + + describe('getInstalledPackageVersion', () => { + const installPackage = (dir: string, content: string) => + writeAppFile(path.join(dir, 'node_modules', '@nativescript', 'vite', 'package.json'), content); + + it('reads the version from the nearest install', () => { + installPackage('.', JSON.stringify({ version: '8.0.22' })); + installPackage('apps/mobile', JSON.stringify({ version: '8.1.0' })); + + expect(getInstalledPackageVersion(appRoot, '@nativescript/vite')).toBe('8.0.22'); + expect(getInstalledPackageVersion(path.join(appRoot, 'apps', 'mobile'), '@nativescript/vite')).toBe('8.1.0'); + }); + + it('walks up to a workspace root install', () => { + installPackage('.', JSON.stringify({ version: '8.0.23' })); + const nested = path.join(appRoot, 'apps', 'mobile'); + fs.mkdirSync(nested, { recursive: true }); + + expect(getInstalledPackageVersion(nested, '@nativescript/vite')).toBe('8.0.23'); + }); + + it('is undefined when the package is missing or its package.json is unreadable', () => { + expect(getInstalledPackageVersion(appRoot, '@nativescript/vite')).toBeUndefined(); + + installPackage('.', '{ not json'); + expect(getInstalledPackageVersion(appRoot, '@nativescript/vite')).toBeUndefined(); + }); + }); + describe('findLocalCli', () => { const installCli = (dir: string, bin = 'ns') => { const file = path.join(appRoot, dir, 'node_modules', '.bin', bin);