diff --git a/src/node/serverPluginModuleRewrite.ts b/src/node/serverPluginModuleRewrite.ts index 2e1aca60ecd932..31678efd42768e 100644 --- a/src/node/serverPluginModuleRewrite.ts +++ b/src/node/serverPluginModuleRewrite.ts @@ -51,13 +51,13 @@ export const moduleRewritePlugin: Plugin = ({ app, watcher, resolver }) => { if (ctx.path === '/index.html') { const html = await readBody(ctx.body) - if (rewriteCache.has(html)) { + if (html && rewriteCache.has(html)) { debug('/index.html: serving from cache') ctx.body = rewriteCache.get(html) } else if (ctx.body) { await initLexer let hasInjectedDevFlag = false - ctx.body = html.replace( + ctx.body = html!.replace( /(]*>)([\s\S]*?)<\/script>/gm, (_, openTag, script) => { // also inject __DEV__ flag @@ -78,6 +78,7 @@ export const moduleRewritePlugin: Plugin = ({ app, watcher, resolver }) => { // this allows us to post-process javascript produced by user middlewares // regardless of the extension of the original files. if ( + ctx.body && ctx.response.is('js') && !ctx.url.endsWith('.map') && // skip internal client @@ -92,7 +93,7 @@ export const moduleRewritePlugin: Plugin = ({ app, watcher, resolver }) => { } else { await initLexer ctx.body = rewriteImports( - content, + content!, ctx.url.replace(/(&|\?)t=\d+/, ''), resolver, ctx.query.t diff --git a/src/node/utils.ts b/src/node/utils.ts index 8b21bd6655bb22..24a0a48a0ca30f 100644 --- a/src/node/utils.ts +++ b/src/node/utils.ts @@ -84,8 +84,8 @@ export async function cachedRead( * Useful in post-processing middlewares. */ export async function readBody( - stream: Readable | Buffer | string -): Promise { + stream: Readable | Buffer | string | null +): Promise { if (stream instanceof Readable) { return new Promise((resolve, reject) => { let res = '' @@ -97,6 +97,6 @@ export async function readBody( }) }) } else { - return typeof stream === 'string' ? stream : stream.toString() + return !stream || typeof stream === 'string' ? stream : stream.toString() } }