Skip to content

Commit

Permalink
Fix image-optimizer requires in next-server (#34141)
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Feb 9, 2022
1 parent 2e0598d commit 28f65ff
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
31 changes: 20 additions & 11 deletions packages/next/server/next-server.ts
Expand Up @@ -95,7 +95,7 @@ export interface NodeRequestHandler {
}

export default class NextNodeServer extends BaseServer {
private imageResponseCache: ResponseCache
private imageResponseCache?: ResponseCache

constructor(options: Options) {
// Initialize super class
Expand All @@ -117,15 +117,17 @@ export default class NextNodeServer extends BaseServer {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}

const { ImageOptimizerCache } =
require('./image-optimizer') as typeof import('./image-optimizer')
if (!this.minimalMode) {
const { ImageOptimizerCache } =
require('./image-optimizer') as typeof import('./image-optimizer')

this.imageResponseCache = new ResponseCache(
new ImageOptimizerCache({
distDir: this.distDir,
nextConfig: this.nextConfig,
})
)
this.imageResponseCache = new ResponseCache(
new ImageOptimizerCache({
distDir: this.distDir,
nextConfig: this.nextConfig,
})
)
}
}

private compression =
Expand Down Expand Up @@ -170,8 +172,6 @@ export default class NextNodeServer extends BaseServer {
}

protected generateImageRoutes(): Route[] {
const { getHash, ImageOptimizerCache, sendResponse, ImageError } =
require('./image-optimizer') as typeof import('./image-optimizer')
return [
{
match: route('/_next/image'),
Expand All @@ -185,6 +185,15 @@ export default class NextNodeServer extends BaseServer {
finished: true,
}
}
const { getHash, ImageOptimizerCache, sendResponse, ImageError } =
require('./image-optimizer') as typeof import('./image-optimizer')

if (!this.imageResponseCache) {
throw new Error(
'invariant image optimizer cache was not initialized'
)
}

const imagesConfig = this.nextConfig.images

if (imagesConfig.loader !== 'default') {
Expand Down
3 changes: 3 additions & 0 deletions test/production/required-server-files.test.ts
Expand Up @@ -21,6 +21,9 @@ describe('should set-up next', () => {
let requiredFilesManifest

beforeAll(async () => {
// test build against environment with next support
process.env.NOW_BUILDER = '1'

next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'required-server-files/pages')),
Expand Down

0 comments on commit 28f65ff

Please sign in to comment.