Skip to content

Commit

Permalink
fix(json): support importing json with ?url and ?raw queries
Browse files Browse the repository at this point in the history
fux #2455
  • Loading branch information
yyx990803 committed Mar 15, 2021
1 parent 24c866f commit fd0a0d9
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
16 changes: 15 additions & 1 deletion packages/playground/json/__tests__/json.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isBuild } from '../../testUtils'

const json = require('../test.json')
const deepJson = require('@vue/runtime-core/package.json')
const stringified = JSON.stringify(json)
Expand Down Expand Up @@ -27,6 +29,18 @@ test('dynamic import, named', async () => {
expect(await page.textContent('.dynamic-named')).toBe(json.hello)
})

test('raw fetch', async () => {
test('fetch', async () => {
expect(await page.textContent('.fetch')).toBe(stringified)
})

test('?url', async () => {
expect(await page.textContent('.url')).toMatch(
isBuild ? 'data:application/json' : '/test.json'
)
})

test('?raw', async () => {
expect(await page.textContent('.raw')).toBe(
require('fs').readFileSync(require.resolve('../test.json'), 'utf-8')
)
})
14 changes: 13 additions & 1 deletion packages/playground/json/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,15 @@ <h2>Dynamic Import</h2>
<pre class="dynamic"></pre>
<pre class="dynamic-named"></pre>

<h2>Raw fetch</h2>
<h2>fetch</h2>
<pre class="fetch"></pre>

<h2>Importing as URL</h2>
<pre class="url"></pre>

<h2>Raw Import</h2>
<pre class="raw"></pre>

<script type="module">
import json, { hello } from './test.json'
import deepJson, { name } from '@vue/runtime-core/package.json'
Expand All @@ -34,6 +40,12 @@ <h2>Raw fetch</h2>
text('.fetch', JSON.stringify(data))
})

import url from './test.json?url'
text('.url', url)

import raw from './test.json?raw'
text('.raw', raw)

function text(sel, text) {
document.querySelector(sel).textContent = text
}
Expand Down
2 changes: 2 additions & 0 deletions packages/vite/src/node/plugins/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { dataToEsm } from '@rollup/pluginutils'
import { Plugin } from 'rollup'
import { SPECIAL_QUERY_RE } from '../constants'

export interface JsonOptions {
/**
Expand Down Expand Up @@ -35,6 +36,7 @@ export function jsonPlugin(

transform(json, id) {
if (!jsonExtRE.test(id)) return null
if (SPECIAL_QUERY_RE.test(id)) return null

try {
if (options.stringify) {
Expand Down

0 comments on commit fd0a0d9

Please sign in to comment.