From 868aa217243da2284bab0eb7fc9e7cc549df8ea1 Mon Sep 17 00:00:00 2001 From: Evan You Date: Thu, 23 Apr 2020 15:33:37 -0400 Subject: [PATCH] feat: add import analysis cache --- src/server/plugins/modules.ts | 53 ++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/src/server/plugins/modules.ts b/src/server/plugins/modules.ts index 5ae5a3372dbeac..973d62cd823ea0 100644 --- a/src/server/plugins/modules.ts +++ b/src/server/plugins/modules.ts @@ -10,12 +10,19 @@ import { promises as fs } from 'fs' import { hmrClientPublicPath } from './hmr' import { parse } from '@babel/parser' import { StringLiteral } from '@babel/types' +import LRUCache from 'lru-cache' const idToFileMap = new Map() const fileToIdMap = new Map() const webModulesMap = new Map() +const rewriteCache = new LRUCache({ max: 65535 }) + +export const modulesPlugin: Plugin = ({ root, app, watcher }) => { + // bust module rewrite cache on file change + watcher.on('change', (file) => { + rewriteCache.del('/' + path.relative(root, file)) + }) -export const modulesPlugin: Plugin = ({ root, app }) => { // rewrite named module imports to `/@modules/:id` requests app.use(async (ctx, next) => { await next() @@ -25,14 +32,19 @@ export const modulesPlugin: Plugin = ({ root, app }) => { } if (ctx.url === '/index.html') { - const html = await readBody(ctx.body) - await initLexer - ctx.body = html.replace( - /(]*>)([\s\S]*?)<\/script>/gm, - (_, openTag, script) => { - return `${openTag}${rewriteImports(script, '/index.html')}` - } - ) + if (rewriteCache.has('/index.html')) { + ctx.body = rewriteCache.get('/index.html') + } else { + const html = await readBody(ctx.body) + await initLexer + ctx.body = html.replace( + /(]*>)([\s\S]*?)<\/script>/gm, + (_, openTag, script) => { + return `${openTag}${rewriteImports(script, '/index.html')}` + } + ) + rewriteCache.set('/index.html', ctx.body) + } } // we are doing the js rewrite after all other middlewares have finished; @@ -40,17 +52,23 @@ export const modulesPlugin: Plugin = ({ root, app }) => { // regardless of the extension of the original files. if ( ctx.response.is('js') && + !ctx.url.endsWith('.map') && // skip internal client !ctx.path.startsWith(`/@hmr`) && // only need to rewrite for