From 73d94b9ba75836b995ed276747a32ce94344c1eb Mon Sep 17 00:00:00 2001 From: Evan You Date: Wed, 6 May 2020 00:10:47 -0400 Subject: [PATCH] fix: fix direct index script src hmr --- src/node/serverPluginModuleRewrite.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/node/serverPluginModuleRewrite.ts b/src/node/serverPluginModuleRewrite.ts index fb2b40563758a7..cde916194541a5 100644 --- a/src/node/serverPluginModuleRewrite.ts +++ b/src/node/serverPluginModuleRewrite.ts @@ -44,6 +44,7 @@ export const moduleRewritePlugin: Plugin = ({ app, watcher, resolver }) => { `\n` const scriptRE = /(]*>)([\s\S]*?)<\/script>/gm + const srcRE = /\bsrc=(?:"([^"]+)"|'([^']+)'|([^'"\s]+)\b)/ app.use(async (ctx, next) => { await next() @@ -60,16 +61,26 @@ export const moduleRewritePlugin: Plugin = ({ app, watcher, resolver }) => { } else if (ctx.body) { await initLexer let hasInjectedDevFlag = false - ctx.body = html!.replace(scriptRE, (_, openTag, script) => { - // also inject __DEV__ flag + const importer = '/index.html' + ctx.body = html!.replace(scriptRE, (matched, openTag, script) => { const devFlag = hasInjectedDevFlag ? `` : devInjectionCode hasInjectedDevFlag = true - const ret = `${devFlag}${openTag}${rewriteImports( - script, - '/index.html', - resolver - )}` - return ret + if (script) { + return `${devFlag}${openTag}${rewriteImports( + script, + importer, + resolver + )}` + } else { + const srcAttr = openTag.match(srcRE) + if (srcAttr) { + // register script as a import dep for hmr + const importee = cleanUrl(slash(path.resolve('/', srcAttr[1]))) + debugHmr(` ${importer} imports ${importee}`) + ensureMapEntry(importerMap, importee).add(importer) + } + return `${devFlag}${matched}` + } }) rewriteCache.set(html, ctx.body) return