From e10530ba2c76374943b2e012800697cd30852fe6 Mon Sep 17 00:00:00 2001 From: zhenzhenChange <1506678296@qq.com> Date: Fri, 17 Jun 2022 15:20:57 +0800 Subject: [PATCH] fix: filter of BOM tags in json plugin (#8628) --- packages/vite/src/node/plugins/importAnalysis.ts | 6 ++---- packages/vite/src/node/plugins/json.ts | 3 +++ packages/vite/src/node/utils.ts | 9 +++++++++ playground/json/index.html | 6 ++++++ playground/json/json-bom/has-bom.json | 4 ++++ 5 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 playground/json/json-bom/has-bom.json diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index b4f5fbfa4..22797c1c0 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -36,6 +36,7 @@ import { normalizePath, prettifyUrl, removeImportQuery, + stripBomTag, timeFrom, transformResult, unwrapId @@ -142,10 +143,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { const start = performance.now() await init let imports: readonly ImportSpecifier[] = [] - // strip UTF-8 BOM - if (source.charCodeAt(0) === 0xfeff) { - source = source.slice(1) - } + source = stripBomTag(source) try { imports = parseImports(source)[0] } catch (e: any) { diff --git a/packages/vite/src/node/plugins/json.ts b/packages/vite/src/node/plugins/json.ts index 9c142501f..216679a22 100644 --- a/packages/vite/src/node/plugins/json.ts +++ b/packages/vite/src/node/plugins/json.ts @@ -9,6 +9,7 @@ import { dataToEsm } from '@rollup/pluginutils' import { SPECIAL_QUERY_RE } from '../constants' import type { Plugin } from '../plugin' +import { stripBomTag } from '../utils' export interface JsonOptions { /** @@ -43,6 +44,8 @@ export function jsonPlugin( if (!jsonExtRE.test(id)) return null if (SPECIAL_QUERY_RE.test(id)) return null + json = stripBomTag(json) + try { if (options.stringify) { if (isBuild) { diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index e36e33c3c..c3c586969 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -1014,3 +1014,12 @@ export function transformResult( map: needSourceMap ? s.generateMap({ hires: true, source: id }) : null } } + +// strip UTF-8 BOM +export function stripBomTag(content: string): string { + if (content.charCodeAt(0) === 0xfeff) { + return content.slice(1) + } + + return content +} diff --git a/playground/json/index.html b/playground/json/index.html index cf16636f9..4c9343652 100644 --- a/playground/json/index.html +++ b/playground/json/index.html @@ -22,6 +22,9 @@