Skip to content

Commit

Permalink
Check if web_modules/import-map.json exists and check it before res…
Browse files Browse the repository at this point in the history
…olving from `node_modules`
  • Loading branch information
Israel Roldán committed Apr 23, 2020
1 parent 6e66766 commit af2db63
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion src/server/plugins/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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>>()
Expand Down

0 comments on commit af2db63

Please sign in to comment.