fix(nitro): filter out duplicate imports (#378)

This commit is contained in:
Daniel Roe 2021-07-26 14:44:35 +01:00 committed by GitHub
parent bad2a74805
commit 956f442e29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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')}