From 03b9674cb294e96ba118600262d22a567c5ae7aa Mon Sep 17 00:00:00 2001 From: Senao <48955231+XiSenao@users.noreply.github.com> Date: Tue, 12 Mar 2024 21:10:04 +0800 Subject: [PATCH] feat: support for self-referencing (#16068) --- packages/vite/src/node/plugins/resolve.ts | 14 +++++++++++++- .../nested-deps/__tests__/nested-deps.spec.ts | 1 + playground/nested-deps/index.html | 6 ++++++ playground/nested-deps/package.json | 3 ++- playground/self-referencing/index.js | 1 + playground/self-referencing/package.json | 8 ++++++++ playground/self-referencing/test/index.js | 1 + pnpm-lock.yaml | 5 +++++ 8 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 playground/self-referencing/index.js create mode 100644 playground/self-referencing/package.json create mode 100644 playground/self-referencing/test/index.js diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index a9b68b1fe..c02f1554a 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -735,7 +735,19 @@ export function tryNodeResolve( basedir = root } - const pkg = resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache) + let selfPkg = null + if (!isBuiltin(id) && !id.includes('\0') && bareImportRE.test(id)) { + // check if it's a self reference dep. + const selfPackageData = findNearestPackageData(basedir, packageCache) + selfPkg = + selfPackageData?.data.exports && selfPackageData?.data.name === pkgId + ? selfPackageData + : null + } + + const pkg = + selfPkg || + resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache) if (!pkg) { // if import can't be found, check if it's an optional peer dep. // if so, we can resolve to a special id that errors only when imported. diff --git a/playground/nested-deps/__tests__/nested-deps.spec.ts b/playground/nested-deps/__tests__/nested-deps.spec.ts index 04618ece5..d59c571db 100644 --- a/playground/nested-deps/__tests__/nested-deps.spec.ts +++ b/playground/nested-deps/__tests__/nested-deps.spec.ts @@ -14,4 +14,5 @@ test('handle nested package', async () => { // expect(await page.textContent('.nested-e')).toBe('1') expect(await page.textContent('.absolute-f')).toBe('F@2.0.0') + expect(await page.textContent('.self-referencing')).toBe('true') }) diff --git a/playground/nested-deps/index.html b/playground/nested-deps/index.html index 86dbc149f..d06916f77 100644 --- a/playground/nested-deps/index.html +++ b/playground/nested-deps/index.html @@ -24,6 +24,9 @@