Unverified Commit e8e85eff authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Support favicon.ico for metadata (#45759

## Feature

* Picking up root favicon (`/app/favicon.ico`) into icons, and add
missing `type` prop for `<link>`
* Fixes the `/favicon.ico` 500 in dev server (`fileExists` checking
part)

Closes NEXT-475

- [x] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [x] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
parent 1e13662d
...@@ -217,6 +217,7 @@ export function getAppEntry(opts: { ...@@ -217,6 +217,7 @@ export function getAppEntry(opts: {
appDir: string appDir: string
appPaths: string[] | null appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
assetPrefix: string
isDev?: boolean isDev?: boolean
rootDir?: string rootDir?: string
tsconfigPath?: string tsconfigPath?: string
...@@ -410,6 +411,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -410,6 +411,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
appDir, appDir,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
assetPrefix: config.assetPrefix,
}) })
} else { } else {
server[serverBundlePath] = [mappings[page]] server[serverBundlePath] = [mappings[page]]
...@@ -426,6 +428,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -426,6 +428,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
appDir: appDir!, appDir: appDir!,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
assetPrefix: config.assetPrefix,
}).import }).import
} }
......
import type webpack from 'webpack'
import type { AppLoaderOptions } from '../next-app-loader'
import path from 'path' import path from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
...@@ -14,6 +16,10 @@ const staticAssetIconsImage = { ...@@ -14,6 +16,10 @@ const staticAssetIconsImage = {
filename: 'apple-icon', filename: 'apple-icon',
extensions: ['jpg', 'jpeg', 'png', 'svg'], extensions: ['jpg', 'jpeg', 'png', 'svg'],
}, },
favicon: {
filename: 'favicon',
extensions: ['ico'],
},
} }
// Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.) // Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.)
...@@ -23,12 +29,10 @@ async function enumMetadataFiles( ...@@ -23,12 +29,10 @@ async function enumMetadataFiles(
extensions: string[], extensions: string[],
{ {
resolvePath, resolvePath,
addDependency, loaderContext,
addMissingDependency,
}: { }: {
resolvePath: (pathname: string) => Promise<string> resolvePath: (pathname: string) => Promise<string>
addDependency: (dep: string) => any loaderContext: webpack.LoaderContext<any>
addMissingDependency: (dep: string) => any
} }
) { ) {
const collectedFiles: string[] = [] const collectedFiles: string[] = []
...@@ -43,14 +47,14 @@ async function enumMetadataFiles( ...@@ -43,14 +47,14 @@ async function enumMetadataFiles(
const pathname = path.join(dir, `${name}.${ext}`) const pathname = path.join(dir, `${name}.${ext}`)
try { try {
const resolved = await resolvePath(pathname) const resolved = await resolvePath(pathname)
addDependency(resolved) loaderContext.addDependency(resolved)
collectedFiles.push(resolved) collectedFiles.push(resolved)
} catch (err: any) { } catch (err: any) {
if (!err.message.includes("Can't resolve")) { if (!err.message.includes("Can't resolve")) {
throw err throw err
} }
addMissingDependency(pathname) loaderContext.addMissingDependency(pathname)
} }
} }
} }
...@@ -61,15 +65,15 @@ async function enumMetadataFiles( ...@@ -61,15 +65,15 @@ async function enumMetadataFiles(
export async function discoverStaticMetadataFiles( export async function discoverStaticMetadataFiles(
resolvedDir: string, resolvedDir: string,
{ {
isDev,
resolvePath, resolvePath,
addDependency, isRootLayer,
addMissingDependency, loaderContext,
loaderOptions,
}: { }: {
isDev: boolean
addDependency: (dep: string) => any
addMissingDependency: (dep: string) => any
resolvePath: (pathname: string) => Promise<string> resolvePath: (pathname: string) => Promise<string>
isRootLayer: boolean
loaderContext: webpack.LoaderContext<any>
loaderOptions: AppLoaderOptions
} }
) { ) {
let hasStaticMetadataFiles = false let hasStaticMetadataFiles = false
...@@ -83,11 +87,15 @@ export async function discoverStaticMetadataFiles( ...@@ -83,11 +87,15 @@ export async function discoverStaticMetadataFiles(
const opts = { const opts = {
resolvePath, resolvePath,
addDependency, loaderContext,
addMissingDependency, }
const metadataImageLoaderOptions = {
isDev: loaderOptions.isDev,
assetPrefix: loaderOptions.assetPrefix,
} }
async function collectIconModuleIfExists(type: 'icon' | 'apple') { async function collectIconModuleIfExists(type: 'icon' | 'apple' | 'favicon') {
const resolvedMetadataFiles = await enumMetadataFiles( const resolvedMetadataFiles = await enumMetadataFiles(
resolvedDir, resolvedDir,
staticAssetIconsImage[type].filename, staticAssetIconsImage[type].filename,
...@@ -98,19 +106,26 @@ export async function discoverStaticMetadataFiles( ...@@ -98,19 +106,26 @@ export async function discoverStaticMetadataFiles(
.sort((a, b) => a.localeCompare(b)) .sort((a, b) => a.localeCompare(b))
.forEach((filepath) => { .forEach((filepath) => {
const iconModule = `() => import(/* webpackMode: "eager" */ ${JSON.stringify( const iconModule = `() => import(/* webpackMode: "eager" */ ${JSON.stringify(
`next-metadata-image-loader?${stringify({ isDev })}!` + `next-metadata-image-loader?${stringify(
metadataImageLoaderOptions
)}!` +
filepath + filepath +
METADATA_IMAGE_RESOURCE_QUERY METADATA_IMAGE_RESOURCE_QUERY
)})` )})`
hasStaticMetadataFiles = true hasStaticMetadataFiles = true
iconsMetadata[type].push(iconModule) if (type === 'favicon') {
iconsMetadata.icon.unshift(iconModule)
} else {
iconsMetadata[type].push(iconModule)
}
}) })
} }
await Promise.all([ await Promise.all([
collectIconModuleIfExists('icon'), collectIconModuleIfExists('icon'),
collectIconModuleIfExists('apple'), collectIconModuleIfExists('apple'),
isRootLayer && collectIconModuleIfExists('favicon'),
]) ])
return hasStaticMetadataFiles ? iconsMetadata : null return hasStaticMetadataFiles ? iconsMetadata : null
......
...@@ -39,9 +39,8 @@ async function createTreeCodeFromPath( ...@@ -39,9 +39,8 @@ async function createTreeCodeFromPath(
resolver, resolver,
resolvePath, resolvePath,
resolveParallelSegments, resolveParallelSegments,
isDev, loaderContext,
addDependency, loaderOptions,
addMissingDependency,
}: { }: {
resolver: ( resolver: (
pathname: string, pathname: string,
...@@ -51,9 +50,8 @@ async function createTreeCodeFromPath( ...@@ -51,9 +50,8 @@ async function createTreeCodeFromPath(
resolveParallelSegments: ( resolveParallelSegments: (
pathname: string pathname: string
) => [key: string, segment: string][] ) => [key: string, segment: string][]
isDev: boolean loaderContext: webpack.LoaderContext<AppLoaderOptions>
addDependency: (dep: string) => any loaderOptions: AppLoaderOptions
addMissingDependency: (dep: string) => any
} }
) { ) {
const splittedPath = pagePath.split(/[\\/]/) const splittedPath = pagePath.split(/[\\/]/)
...@@ -72,10 +70,11 @@ async function createTreeCodeFromPath( ...@@ -72,10 +70,11 @@ async function createTreeCodeFromPath(
// Existing tree are the children of the current segment // Existing tree are the children of the current segment
const props: Record<string, string> = {} const props: Record<string, string> = {}
const isRootLayer = segments.length === 0
// We need to resolve all parallel routes in this level. // We need to resolve all parallel routes in this level.
const parallelSegments: [key: string, segment: string][] = [] const parallelSegments: [key: string, segment: string][] = []
if (segments.length === 0) { if (isRootLayer) {
parallelSegments.push(['children', '']) parallelSegments.push(['children', ''])
} else { } else {
parallelSegments.push(...resolveParallelSegments(segmentPath)) parallelSegments.push(...resolveParallelSegments(segmentPath))
...@@ -88,10 +87,10 @@ async function createTreeCodeFromPath( ...@@ -88,10 +87,10 @@ async function createTreeCodeFromPath(
if (resolvedRouteDir) { if (resolvedRouteDir) {
metadata = await discoverStaticMetadataFiles(resolvedRouteDir, { metadata = await discoverStaticMetadataFiles(resolvedRouteDir, {
isDev,
resolvePath, resolvePath,
addDependency, isRootLayer,
addMissingDependency, loaderContext,
loaderOptions,
}) })
} }
} catch (err: any) { } catch (err: any) {
...@@ -144,7 +143,7 @@ async function createTreeCodeFromPath( ...@@ -144,7 +143,7 @@ async function createTreeCodeFromPath(
if (!globalError) { if (!globalError) {
globalError = await resolver( globalError = await resolver(
`${appDirPrefix}${parallelSegmentPath}/${GLOBAL_ERROR_FILE_TYPE}` `${appDirPrefix}${parallelSegmentPath}${GLOBAL_ERROR_FILE_TYPE}`
) )
} }
...@@ -195,16 +194,22 @@ function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) { ...@@ -195,16 +194,22 @@ function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) {
) )
} }
const nextAppLoader: webpack.LoaderDefinitionFunction<{ export type AppLoaderOptions = {
name: string name: string
pagePath: string pagePath: string
appDir: string appDir: string
appPaths: string[] | null appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
basePath: string
assetPrefix: string
rootDir?: string rootDir?: string
tsconfigPath?: string tsconfigPath?: string
isDev?: boolean isDev?: boolean
}> = async function nextAppLoader() { }
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
const nextAppLoader: AppLoader = async function nextAppLoader() {
const loaderOptions = this.getOptions() || {}
const { const {
name, name,
appDir, appDir,
...@@ -214,7 +219,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -214,7 +219,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
rootDir, rootDir,
tsconfigPath, tsconfigPath,
isDev, isDev,
} = this.getOptions() || {} } = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
buildInfo.route = { buildInfo.route = {
...@@ -284,9 +289,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -284,9 +289,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
resolver, resolver,
resolvePath: (pathname: string) => resolve(this.rootContext, pathname), resolvePath: (pathname: string) => resolve(this.rootContext, pathname),
resolveParallelSegments, resolveParallelSegments,
isDev: !!isDev, loaderContext: this,
addDependency: this.addDependency.bind(this), loaderOptions: loaderOptions,
addMissingDependency: this.addMissingDependency.bind(this),
}) })
if (!rootLayout) { if (!rootLayout) {
......
...@@ -5,18 +5,18 @@ interface Options { ...@@ -5,18 +5,18 @@ interface Options {
isServer: boolean isServer: boolean
isDev: boolean isDev: boolean
assetPrefix: string assetPrefix: string
basePath: string
} }
const mimeTypeMap = {
jpeg: 'image/jpeg',
png: 'image/png',
ico: 'image/x-icon',
svg: 'image/svg+xml',
} as const
async function nextMetadataImageLoader(this: any, content: Buffer) { async function nextMetadataImageLoader(this: any, content: Buffer) {
const options: Options = this.getOptions() const options: Options = this.getOptions()
const { const { assetPrefix, isDev } = options
// TODO-APP: support assetPrefix
assetPrefix = '',
// isServer,
isDev,
// basePath
} = options
const context = this.rootContext const context = this.rootContext
const opts = { context, content } const opts = { context, content }
...@@ -43,7 +43,11 @@ async function nextMetadataImageLoader(this: any, content: Buffer) { ...@@ -43,7 +43,11 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const stringifiedData = JSON.stringify({ const stringifiedData = JSON.stringify({
url: outputPath, url: outputPath,
sizes: `${imageSize.width}x${imageSize.height}`, ...(extension in mimeTypeMap && {
type: mimeTypeMap[extension as keyof typeof mimeTypeMap],
}),
sizes:
extension === 'ico' ? 'any' : `${imageSize.width}x${imageSize.height}`,
}) })
this.emitFile(`../${isDev ? '' : '../'}${interpolatedName}`, content, null) this.emitFile(`../${isDev ? '' : '../'}${interpolatedName}`, content, null)
......
...@@ -654,6 +654,7 @@ export default class HotReloader { ...@@ -654,6 +654,7 @@ export default class HotReloader {
rootDir: this.dir, rootDir: this.dir,
isDev: true, isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath, tsconfigPath: this.config.typescript.tsconfigPath,
assetPrefix: this.config.assetPrefix,
}).import }).import
: undefined : undefined
...@@ -735,6 +736,7 @@ export default class HotReloader { ...@@ -735,6 +736,7 @@ export default class HotReloader {
rootDir: this.dir, rootDir: this.dir,
isDev: true, isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath, tsconfigPath: this.config.typescript.tsconfigPath,
assetPrefix: this.config.assetPrefix,
}) })
: relativeRequest, : relativeRequest,
hasAppDir, hasAppDir,
......
...@@ -37,7 +37,12 @@ export async function findPageFile( ...@@ -37,7 +37,12 @@ export async function findPageFile(
await Promise.all( await Promise.all(
pagePaths.map(async (path) => { pagePaths.map(async (path) => {
const filePath = join(pagesDir, path) const filePath = join(pagesDir, path)
return (await fileExists(filePath)) ? path : null try {
return (await fileExists(filePath)) ? path : null
} catch (err: any) {
if (!err?.code?.includes('ENOTDIR')) throw err
}
return null
}) })
) )
).filter(nonNullable) ).filter(nonNullable)
......
...@@ -10,6 +10,7 @@ export default function page(props) { ...@@ -10,6 +10,7 @@ export default function page(props) {
export async function generateMetadata(props, parent) { export async function generateMetadata(props, parent) {
const parentMetadata = await parent const parentMetadata = await parent
return { return {
...parentMetadata, ...parentMetadata,
title: format(props), title: format(props),
......
...@@ -454,6 +454,23 @@ createNextDescribe( ...@@ -454,6 +454,23 @@ createNextDescribe(
]) ])
).toEqual({ sizes: '180x180', type: 'image/png' }) ).toEqual({ sizes: '180x180', type: 'image/png' })
}) })
it('should support root level of favicon.ico', async () => {
let $ = await next.render$('/')
let $icon = $('link[rel="icon"]')
expect($icon.attr('href')).toMatch(
/_next\/static\/media\/metadata\/favicon.\w+.ico/
)
expect($icon.attr('type')).toBe('image/x-icon')
expect($icon.attr('sizes')).toBe('any')
$ = await next.render$('/basic')
$icon = $('link[rel="icon"]')
expect($icon.attr('href')).toMatch(
/_next\/static\/media\/metadata\/favicon.\w+.ico/
)
expect($icon.attr('sizes')).toBe('any')
})
}) })
describe('file based icons', () => { describe('file based icons', () => {
...@@ -467,9 +484,11 @@ createNextDescribe( ...@@ -467,9 +484,11 @@ createNextDescribe(
/\/_next\/static\/media\/metadata\/icon1\.\w+\.png/ /\/_next\/static\/media\/metadata\/icon1\.\w+\.png/
) )
expect($icon.attr('sizes')).toBe('32x32') expect($icon.attr('sizes')).toBe('32x32')
expect($icon.attr('type')).toBe('image/png')
expect($appleIcon.attr('href')).toMatch( expect($appleIcon.attr('href')).toMatch(
/\/_next\/static\/media\/metadata\/apple-icon\.\w+\.png/ /\/_next\/static\/media\/metadata\/apple-icon\.\w+\.png/
) )
expect($appleIcon.attr('type')).toBe('image/png')
expect($appleIcon.attr('sizes')).toMatch('114x114') expect($appleIcon.attr('sizes')).toMatch('114x114')
}) })
......
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