mirror of
https://github.com/vitejs/vite.git
synced 2024-11-22 07:09:05 +00:00
feat: support resolving snowpack web_modules (#4)
This commit is contained in:
parent
6e66766c85
commit
a18379177c
@ -6,9 +6,11 @@ import { Readable } from 'stream'
|
||||
import { init as initLexer, parse } from 'es-module-lexer'
|
||||
import MagicString from 'magic-string'
|
||||
import { cachedRead } from '../utils'
|
||||
import { promises as fs } from 'fs'
|
||||
|
||||
const idToFileMap = new Map()
|
||||
const fileToIdMap = new Map()
|
||||
const webModulesMap = new Map()
|
||||
|
||||
export const modulesPlugin: Plugin = ({ root, app }) => {
|
||||
// rewrite named module imports to `/__modules/:id` requests
|
||||
@ -99,7 +101,18 @@ export const modulesPlugin: Plugin = ({ root, app }) => {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO support resolving from Snowpack's web_modules
|
||||
try {
|
||||
const webModulePath = await resolveWebModule(root, id)
|
||||
if (webModulePath) {
|
||||
idToFileMap.set(id, webModulePath)
|
||||
fileToIdMap.set(path.basename(webModulePath), id)
|
||||
ctx.body = await cachedRead(webModulePath)
|
||||
return
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
ctx.status = 404
|
||||
}
|
||||
|
||||
// resolve from node_modules
|
||||
try {
|
||||
@ -135,6 +148,29 @@ async function readBody(stream: Readable | string): Promise<string> {
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveWebModule(
|
||||
root: string,
|
||||
id: string
|
||||
): Promise<string | undefined> {
|
||||
const webModulePath = webModulesMap.get(id)
|
||||
if (webModulePath) {
|
||||
return webModulePath
|
||||
}
|
||||
const importMapPath = path.join(root, 'web_modules', 'import-map.json')
|
||||
if (await fs.stat(importMapPath).catch((e) => false)) {
|
||||
const importMap = require(importMapPath)
|
||||
if (importMap.imports) {
|
||||
const webModulesDir = path.dirname(importMapPath)
|
||||
Object.entries(
|
||||
importMap.imports
|
||||
).forEach(([key, val]: [string, string]) =>
|
||||
webModulesMap.set(key, path.join(webModulesDir, val))
|
||||
)
|
||||
return webModulesMap.get(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// while we lex the files for imports we also build a import graph
|
||||
// so that we can determine what files to hot reload
|
||||
export const importerMap = new Map<string, Set<string>>()
|
||||
|
Loading…
Reference in New Issue
Block a user