From 902567ac5327e915ce65d090045fa4922ef9f2b5 Mon Sep 17 00:00:00 2001 From: sapenlei <2503404258gl@gmail.com> Date: Tue, 24 Dec 2024 16:17:44 +0800 Subject: [PATCH] fix(resolve): handle package.json with UTF-8 BOM (#19000) --- packages/vite/src/node/packages.ts | 3 ++- playground/resolve/__tests__/resolve.spec.ts | 4 +++ playground/resolve/index.html | 6 +++++ playground/resolve/package.json | 3 ++- playground/resolve/utf8-bom-package/index.mjs | 1 + .../resolve/utf8-bom-package/package.json | 8 ++++++ pnpm-lock.yaml | 25 +++++++++++++++++++ 7 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 playground/resolve/utf8-bom-package/index.mjs create mode 100644 playground/resolve/utf8-bom-package/package.json diff --git a/packages/vite/src/node/packages.ts b/packages/vite/src/node/packages.ts index 468fc4cbb0595b..5d50f285ee3fa5 100644 --- a/packages/vite/src/node/packages.ts +++ b/packages/vite/src/node/packages.ts @@ -6,6 +6,7 @@ import { isInNodeModules, normalizePath, safeRealpathSync, + stripBomTag, tryStatSync, } from './utils' import type { Plugin } from './plugin' @@ -175,7 +176,7 @@ export function findNearestMainPackageData( } export function loadPackageData(pkgPath: string): PackageData { - const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) + const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, 'utf-8'))) const pkgDir = normalizePath(path.dirname(pkgPath)) const { sideEffects } = data let hasSideEffects: (id: string) => boolean | null diff --git a/playground/resolve/__tests__/resolve.spec.ts b/playground/resolve/__tests__/resolve.spec.ts index e12ddecedb5c0d..ba5e6441dc7edb 100644 --- a/playground/resolve/__tests__/resolve.spec.ts +++ b/playground/resolve/__tests__/resolve.spec.ts @@ -248,3 +248,7 @@ test.runIf(isBuild)('public dir is not copied', async () => { fs.existsSync(path.resolve(testDir, 'dist/should-not-be-copied')), ).toBe(false) }) + +test('import utf8-bom package', async () => { + expect(await page.textContent('.utf8-bom-package')).toMatch('[success]') +}) diff --git a/playground/resolve/index.html b/playground/resolve/index.html index 8c315f74dcd2c1..f1480b0a9b3e52 100644 --- a/playground/resolve/index.html +++ b/playground/resolve/index.html @@ -176,6 +176,9 @@

resolve package that contains # in path

resolve non normalized absolute path

+

utf8-bom-package

+

fail

+