Skip to content

Commit fd0a0d9

Browse files
committed
fix(json): support importing json with ?url and ?raw queries
fux #2455
1 parent 24c866f commit fd0a0d9

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

packages/playground/json/__tests__/json.spec.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isBuild } from '../../testUtils'
2+
13
const json = require('../test.json')
24
const deepJson = require('@vue/runtime-core/package.json')
35
const stringified = JSON.stringify(json)
@@ -27,6 +29,18 @@ test('dynamic import, named', async () => {
2729
expect(await page.textContent('.dynamic-named')).toBe(json.hello)
2830
})
2931

30-
test('raw fetch', async () => {
32+
test('fetch', async () => {
3133
expect(await page.textContent('.fetch')).toBe(stringified)
3234
})
35+
36+
test('?url', async () => {
37+
expect(await page.textContent('.url')).toMatch(
38+
isBuild ? 'data:application/json' : '/test.json'
39+
)
40+
})
41+
42+
test('?raw', async () => {
43+
expect(await page.textContent('.raw')).toBe(
44+
require('fs').readFileSync(require.resolve('../test.json'), 'utf-8')
45+
)
46+
})

packages/playground/json/index.html

+13-1
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,15 @@ <h2>Dynamic Import</h2>
1010
<pre class="dynamic"></pre>
1111
<pre class="dynamic-named"></pre>
1212

13-
<h2>Raw fetch</h2>
13+
<h2>fetch</h2>
1414
<pre class="fetch"></pre>
1515

16+
<h2>Importing as URL</h2>
17+
<pre class="url"></pre>
18+
19+
<h2>Raw Import</h2>
20+
<pre class="raw"></pre>
21+
1622
<script type="module">
1723
import json, { hello } from './test.json'
1824
import deepJson, { name } from '@vue/runtime-core/package.json'
@@ -34,6 +40,12 @@ <h2>Raw fetch</h2>
3440
text('.fetch', JSON.stringify(data))
3541
})
3642

43+
import url from './test.json?url'
44+
text('.url', url)
45+
46+
import raw from './test.json?raw'
47+
text('.raw', raw)
48+
3749
function text(sel, text) {
3850
document.querySelector(sel).textContent = text
3951
}

packages/vite/src/node/plugins/json.ts

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import { dataToEsm } from '@rollup/pluginutils'
1010
import { Plugin } from 'rollup'
11+
import { SPECIAL_QUERY_RE } from '../constants'
1112

1213
export interface JsonOptions {
1314
/**
@@ -35,6 +36,7 @@ export function jsonPlugin(
3536

3637
transform(json, id) {
3738
if (!jsonExtRE.test(id)) return null
39+
if (SPECIAL_QUERY_RE.test(id)) return null
3840

3941
try {
4042
if (options.stringify) {

0 commit comments

Comments
 (0)