fix(data): watch files outside the site root (#5441)

pull/5444/head
lllleolin-max 2 weeks ago committed by GitHub
parent 6500851eaa
commit ac1081f6e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,10 @@
import { readFile } from 'node:fs/promises'
export default {
watch: '../../fixtures/external-data/**/*.json',
async load(files: string[]) {
return Promise.all(
files.map(async (file) => JSON.parse(await readFile(file, 'utf-8')))
)
}
}

@ -0,0 +1,7 @@
<script setup>
import { data } from './files.data'
</script>
# External data
<pre id="external-data">{{ JSON.stringify(data) }}</pre>

@ -0,0 +1,45 @@
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
test('loads data outside the site root', async () => {
await goto('/external-data/')
expect(await page.textContent('pre#external-data')).toBe('[{"a":true}]')
})
test.runIf(!process.env.VITE_TEST_BUILD)(
'updates external data when files change, are added, or are deleted',
async () => {
await goto('/external-data/')
const a = fileURLToPath(
new URL('../../fixtures/external-data/a.json', import.meta.url)
)
const nested = fileURLToPath(
new URL('../../fixtures/external-data/nested/', import.meta.url)
)
const original = await readFile(a, 'utf-8')
async function expectData(data: unknown) {
await page.waitForFunction(
(expected) =>
document.querySelector('pre#external-data')?.textContent === expected,
JSON.stringify(data)
)
}
try {
await writeFile(a, '{"a":false}\n')
await expectData([{ a: false }])
await mkdir(nested)
await writeFile(path.join(nested, 'b.json'), '{"b":true}\n')
await expectData([{ a: false }, { b: true }])
await rm(nested, { recursive: true })
await expectData([{ a: false }])
} finally {
await rm(nested, { recursive: true, force: true })
await writeFile(a, original)
}
}
)

@ -128,6 +128,14 @@ async function loadData(id: string): Promise<string> {
watch = normalizeGlob(loaderModule.watch, base) watch = normalizeGlob(loaderModule.watch, base)
load = loaderModule.load load = loaderModule.load
options = loaderModule.options || {} options = loaderModule.options || {}
// Vite only watches the site root by default. Watch the glob bases too,
// so external files (including newly created ones) can trigger HMR.
server?.watcher.add(
watch
.filter((pattern) => !pattern.startsWith('!'))
.map((pattern) => pm.scan(pattern).base)
)
} }
// load the data // load the data

Loading…
Cancel
Save