Nuxt/packages/vite/src/plugins/virtual.ts
Dario Merz 31c67ad9b4
fix(vite): ignore virtual imports that aren't in vfs (#4822)
Co-authored-by: Dario Merz <dario.merz@deptagency.com>
Co-authored-by: Daniel Roe <daniel@roe.dev>
2022-05-06 15:33:32 +02:00

49 lines
1.3 KiB
TypeScript

import { dirname, isAbsolute, join, resolve } from 'pathe'
import type { Plugin } from 'rollup'
const PREFIX = 'virtual:nuxt:'
export default function virtual (vfs: Record<string, string>): Plugin {
const extensions = ['', '.ts', '.vue', '.mjs', '.cjs', '.js', '.json']
const resolveWithExt = (id) => {
for (const ext of extensions) {
const rId = id + ext
if (rId in vfs) {
return rId
}
}
return null
}
return {
name: 'virtual',
resolveId (id, importer) {
if (process.platform === 'win32' && isAbsolute(id)) {
// Add back C: prefix on Windows
id = resolve(id)
}
const resolvedId = resolveWithExt(id)
if (resolvedId) { return PREFIX + resolvedId }
if (importer && !isAbsolute(id)) {
const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer
const importedDir = dirname(importerNoPrefix)
const resolved = resolveWithExt(join(importedDir, id))
if (resolved) { return PREFIX + resolved }
}
return null
},
load (id) {
if (!id.startsWith(PREFIX)) { return null }
const idNoPrefix = id.slice(PREFIX.length)
if (idNoPrefix in vfs) {
return {
code: vfs[idNoPrefix],
map: null
}
}
}
}
}