Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use modules from web_modules if present #4

Merged
merged 1 commit into from
Apr 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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