From 956f442e29d23197d413b9ba5d2b952accae2e3f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 26 Jul 2021 14:44:35 +0100 Subject: [PATCH] fix(nitro): filter out duplicate imports (#378) --- packages/nitro/src/rollup/plugins/middleware.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/nitro/src/rollup/plugins/middleware.ts b/packages/nitro/src/rollup/plugins/middleware.ts index a2029dbeb8..9d000da6b2 100644 --- a/packages/nitro/src/rollup/plugins/middleware.ts +++ b/packages/nitro/src/rollup/plugins/middleware.ts @@ -6,6 +6,8 @@ import stdenv from 'std-env' import type { ServerMiddleware } from '../../server/middleware' import virtual from './virtual' +const unique = (arr: any[]) => Array.from(new Set(arr)) + export function middleware (getMiddleware: () => ServerMiddleware[]) { const getImportId = p => '_' + hasha(p).substr(0, 6) @@ -26,10 +28,16 @@ export function middleware (getMiddleware: () => ServerMiddleware[]) { } } - return ` - ${middleware.filter(m => m.lazy === false).map(m => `import ${getImportId(m.handle)} from '${m.handle}';`).join('\n')} + // Imports take priority + const imports = unique(middleware.filter(m => m.lazy === false).map(m => m.handle)) - ${middleware.filter(m => m.lazy !== false).map(m => `const ${getImportId(m.handle)} = () => import('${m.handle}');`).join('\n')} + // Lazy imports should fill in the gaps + const lazyImports = unique(middleware.filter(m => m.lazy !== false && !imports.includes(m.handle)).map(m => m.handle)) + + return ` + ${imports.map(handle => `import ${getImportId(handle)} from '${handle}';`).join('\n')} + + ${lazyImports.map(handle => `const ${getImportId(handle)} = () => import('${handle}');`).join('\n')} const middleware = [ ${middleware.map(m => `{ route: '${m.route}', handle: ${getImportId(m.handle)}, lazy: ${m.lazy || true}, promisify: ${m.promisify !== undefined ? m.promisify : true} }`).join(',\n')}