2021-09-27 12:49:36 +00:00
|
|
|
import { dirname, isAbsolute, join, resolve } from 'pathe'
|
2023-03-31 09:56:10 +00:00
|
|
|
import type { Plugin } from 'vite'
|
2021-07-15 10:18:34 +00:00
|
|
|
|
2022-05-06 13:33:32 +00:00
|
|
|
const PREFIX = 'virtual:nuxt:'
|
2021-07-15 10:18:34 +00:00
|
|
|
|
|
|
|
export default function virtual (vfs: Record<string, string>): Plugin {
|
|
|
|
const extensions = ['', '.ts', '.vue', '.mjs', '.cjs', '.js', '.json']
|
2022-08-15 13:40:06 +00:00
|
|
|
const resolveWithExt = (id: string) => {
|
2021-07-15 10:18:34 +00:00
|
|
|
for (const ext of extensions) {
|
|
|
|
const rId = id + ext
|
|
|
|
if (rId in vfs) {
|
|
|
|
return rId
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
name: 'virtual',
|
|
|
|
|
|
|
|
resolveId (id, importer) {
|
2021-08-09 18:24:52 +00:00
|
|
|
if (process.platform === 'win32' && isAbsolute(id)) {
|
|
|
|
// Add back C: prefix on Windows
|
|
|
|
id = resolve(id)
|
|
|
|
}
|
2021-07-15 10:18:34 +00:00
|
|
|
const resolvedId = resolveWithExt(id)
|
|
|
|
if (resolvedId) { return PREFIX + resolvedId }
|
2021-08-09 18:24:52 +00:00
|
|
|
if (importer && !isAbsolute(id)) {
|
2021-07-15 10:18:34 +00:00
|
|
|
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)
|
2022-05-06 13:33:32 +00:00
|
|
|
if (idNoPrefix in vfs) {
|
|
|
|
return {
|
|
|
|
code: vfs[idNoPrefix],
|
|
|
|
map: null
|
|
|
|
}
|
2021-07-15 10:18:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|