Unverified Commit 8aa9a52c authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix tree shaking for image generation module (#51950)

### Issue

When the og module is a shared module being imported in both page and metadata image routes, it will be shared in the module graph. Especially in the edge runtime, since the `default` export is being used in the metadata image routes, then it can't be easily tree-shaked out.

### Solution

Separate the image route to a separate layer which won't share modules with the page, so that image route is always bundling separately and the `@vercel/og` module only stays inside in that layer, when import image metadata named exports (size / alt / etc..) it can be still tree shaked.
Co-authored-by: 's avatarJiachi Liu <4800338+huozhi@users.noreply.github.com>
parent 9bd5169d
...@@ -2022,6 +2022,16 @@ export default async function getBaseWebpackConfig( ...@@ -2022,6 +2022,16 @@ export default async function getBaseWebpackConfig(
} as any, } as any,
] ]
: []), : []),
...(hasAppDir
? [
{
resourceQuery: new RegExp(
WEBPACK_RESOURCE_QUERIES.metadataRoute
),
layer: WEBPACK_LAYERS.metadataImage,
},
]
: []),
...(hasAppDir && isEdgeServer ...(hasAppDir && isEdgeServer
? [ ? [
// The Edge bundle includes the server in its entrypoint, so it has to // The Edge bundle includes the server in its entrypoint, so it has to
...@@ -2181,7 +2191,11 @@ export default async function getBaseWebpackConfig( ...@@ -2181,7 +2191,11 @@ export default async function getBaseWebpackConfig(
issuer: { not: regexLikeCss }, issuer: { not: regexLikeCss },
dependency: { not: ['url'] }, dependency: { not: ['url'] },
resourceQuery: { resourceQuery: {
not: [new RegExp(WEBPACK_RESOURCE_QUERIES.metadata)], not: [
new RegExp(WEBPACK_RESOURCE_QUERIES.metadata),
new RegExp(WEBPACK_RESOURCE_QUERIES.metadataRoute),
new RegExp(WEBPACK_RESOURCE_QUERIES.metadataImageMeta),
],
}, },
options: { options: {
isDev: dev, isDev: dev,
......
...@@ -109,6 +109,7 @@ export async function createStaticMetadataFromRoute( ...@@ -109,6 +109,7 @@ export async function createStaticMetadataFromRoute(
basePath, basePath,
pageExtensions, pageExtensions,
} }
// WEBPACK_RESOURCE_QUERIES.metadata query here only for filtering out applying to image loader
)}!${filepath}?${WEBPACK_RESOURCE_QUERIES.metadata}` )}!${filepath}?${WEBPACK_RESOURCE_QUERIES.metadata}`
const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify( const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify(
......
...@@ -22,6 +22,7 @@ import { RouteKind } from '../../../server/future/route-kind' ...@@ -22,6 +22,7 @@ import { RouteKind } from '../../../server/future/route-kind'
import { AppRouteRouteModuleOptions } from '../../../server/future/route-modules/app-route/module' import { AppRouteRouteModuleOptions } from '../../../server/future/route-modules/app-route/module'
import { AppBundlePathNormalizer } from '../../../server/future/normalizers/built/app/app-bundle-path-normalizer' import { AppBundlePathNormalizer } from '../../../server/future/normalizers/built/app/app-bundle-path-normalizer'
import { MiddlewareConfig } from '../../analysis/get-page-static-info' import { MiddlewareConfig } from '../../analysis/get-page-static-info'
import { getFilenameAndExtension } from './next-metadata-route-loader'
export type AppLoaderOptions = { export type AppLoaderOptions = {
name: string name: string
...@@ -105,10 +106,13 @@ async function createAppRouteCode({ ...@@ -105,10 +106,13 @@ async function createAppRouteCode({
// the route to ensure that the route is generated. // the route to ensure that the route is generated.
const filename = path.parse(resolvedPagePath).name const filename = path.parse(resolvedPagePath).name
if (isMetadataRoute(name) && filename !== 'route') { if (isMetadataRoute(name) && filename !== 'route') {
const { ext } = getFilenameAndExtension(resolvedPagePath)
const isDynamic = pageExtensions.includes(ext)
resolvedPagePath = `next-metadata-route-loader?${stringify({ resolvedPagePath = `next-metadata-route-loader?${stringify({
page, page,
pageExtensions, isDynamic: isDynamic ? '1' : '0',
})}!${resolvedPagePath + '?' + WEBPACK_RESOURCE_QUERIES.metadata}` })}!${resolvedPagePath}${`?${WEBPACK_RESOURCE_QUERIES.metadataRoute}`}`
} }
// References the route handler file to load found in `./routes/${kind}.ts`. // References the route handler file to load found in `./routes/${kind}.ts`.
......
...@@ -50,9 +50,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -50,9 +50,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
const modulePath = `${appDirLoader}${stringifiedPagePath.substring( const modulePath = `${appDirLoader}${stringifiedPagePath.substring(
1, 1,
stringifiedPagePath.length - 1 stringifiedPagePath.length - 1
)}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}&${ )}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}`
WEBPACK_RESOURCE_QUERIES.metadata
}`
return ` return `
import { EdgeRouteModuleWrapper } from 'next/dist/esm/server/web/edge-route-module-wrapper' import { EdgeRouteModuleWrapper } from 'next/dist/esm/server/web/edge-route-module-wrapper'
......
...@@ -82,6 +82,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) { ...@@ -82,6 +82,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
.map((dep: any) => { .map((dep: any) => {
return dep.name return dep.name
}) || [] }) || []
// re-export and spread as `exportedImageData` to avoid non-exported error // re-export and spread as `exportedImageData` to avoid non-exported error
return `\ return `\
import { import {
......
...@@ -2,7 +2,6 @@ import type webpack from 'webpack' ...@@ -2,7 +2,6 @@ import type webpack from 'webpack'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { imageExtMimeTypeMap } from '../../../lib/mime-type' import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
const cacheHeader = { const cacheHeader = {
none: 'no-cache, no-store', none: 'no-cache, no-store',
...@@ -12,10 +11,10 @@ const cacheHeader = { ...@@ -12,10 +11,10 @@ const cacheHeader = {
type MetadataRouteLoaderOptions = { type MetadataRouteLoaderOptions = {
page: string page: string
pageExtensions: string[] isDynamic: '1' | '0'
} }
function getFilenameAndExtension(resourcePath: string) { export function getFilenameAndExtension(resourcePath: string) {
const filename = path.basename(resourcePath) const filename = path.basename(resourcePath)
const [name, ext] = filename.split('.') const [name, ext] = filename.split('.')
return { name, ext } return { name, ext }
...@@ -49,11 +48,7 @@ import { NextResponse } from 'next/server' ...@@ -49,11 +48,7 @@ import { NextResponse } from 'next/server'
const contentType = ${JSON.stringify(getContentType(resourcePath))} const contentType = ${JSON.stringify(getContentType(resourcePath))}
const buffer = Buffer.from(${JSON.stringify( const buffer = Buffer.from(${JSON.stringify(
( (await fs.promises.readFile(resourcePath)).toString('base64')
await fs.promises.readFile(
resourcePath.replace('?' + WEBPACK_RESOURCE_QUERIES.metadata, '')
)
).toString('base64')
)}, 'base64' )}, 'base64'
) )
...@@ -205,13 +200,11 @@ ${staticGenerationCode} ...@@ -205,13 +200,11 @@ ${staticGenerationCode}
const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> = const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> =
async function () { async function () {
const { resourcePath } = this const { resourcePath } = this
const { pageExtensions, page } = this.getOptions() const { page, isDynamic } = this.getOptions()
const { name: fileBaseName } = getFilenameAndExtension(resourcePath)
const { name: fileBaseName, ext } = getFilenameAndExtension(resourcePath)
const isDynamic = pageExtensions.includes(ext)
let code = '' let code = ''
if (isDynamic) { if (isDynamic === '1') {
if (fileBaseName === 'robots' || fileBaseName === 'manifest') { if (fileBaseName === 'robots' || fileBaseName === 'manifest') {
code = getDynamicTextRouteCode(resourcePath) code = getDynamicTextRouteCode(resourcePath)
} else if (fileBaseName === 'sitemap') { } else if (fileBaseName === 'sitemap') {
......
...@@ -95,10 +95,12 @@ export const WEBPACK_LAYERS = { ...@@ -95,10 +95,12 @@ export const WEBPACK_LAYERS = {
middleware: 'middleware', middleware: 'middleware',
edgeAsset: 'edge-asset', edgeAsset: 'edge-asset',
appClient: 'app-client', appClient: 'app-client',
metadataImage: 'app-metadata-image',
} }
export const WEBPACK_RESOURCE_QUERIES = { export const WEBPACK_RESOURCE_QUERIES = {
edgeSSREntry: '__next_edge_ssr_entry__', edgeSSREntry: '__next_edge_ssr_entry__',
metadata: '__next_metadata__', metadata: '__next_metadata__',
metadataRoute: '__next_metadata_route__',
metadataImageMeta: '__next_metadata_image_meta__', metadataImageMeta: '__next_metadata_image_meta__',
} }
export const alt = 'Open Graph Edge'
export const runtime = 'edge'
export { default } from '../og'
import React from 'react'
export default function Page() {
return <>hello another</>
}
export const metadata = {
title: 'another page',
}
export const runtime = 'edge'
import { ImageResponse } from 'next/server'
export default function og() {
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 128,
background: 'lavender',
}}
>
Open Graph
</div>
)
)
}
import { ImageResponse } from 'next/server'
export const alt = 'Open Graph' export const alt = 'Open Graph'
export default function og() { export { default } from './og'
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 128,
background: 'lavender',
}}
>
Open Graph
</div>
)
)
}
...@@ -10,10 +10,13 @@ createNextDescribe( ...@@ -10,10 +10,13 @@ createNextDescribe(
describe('OG image route', () => { describe('OG image route', () => {
if (isNextStart) { if (isNextStart) {
it('should not bundle `ImageResponse` into the page worker', async () => { it('should not bundle `ImageResponse` into the page worker', async () => {
const pageBundle = await next.readFile( const pageBundle = await next.readFile('.next/server/app/page.js')
'.next/server/middleware-manifest.json'
)
expect(pageBundle).not.toContain('ImageResponse') expect(pageBundle).not.toContain('ImageResponse')
const sharedPageBundle = await next.readFile(
'.next/server/app/another/page.js'
)
expect(sharedPageBundle).not.toContain('ImageResponse')
}) })
} }
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment