Unverified Commit 3ab6d179 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Remove `optimizeFonts` (Automatic font optimization) superseded by next/font (#69137)

## What?

The `optimizeFonts` optimization has been replaced by `next/font` for
almost 2 years and was already no longer documented. This PR cleans up
the code related to it. It's recommended to use `next/font` as it's
better in every way, ensuring you get preloading of the font but also a
local fallback and better fallbacks.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 161cd00c
...@@ -17,7 +17,6 @@ import { ...@@ -17,7 +17,6 @@ import {
APP_BUILD_MANIFEST, APP_BUILD_MANIFEST,
APP_PATH_ROUTES_MANIFEST, APP_PATH_ROUTES_MANIFEST,
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
BUILD_MANIFEST, BUILD_MANIFEST,
CLIENT_REFERENCE_MANIFEST, CLIENT_REFERENCE_MANIFEST,
FUNCTIONS_CONFIG_MANIFEST, FUNCTIONS_CONFIG_MANIFEST,
...@@ -366,22 +365,6 @@ export async function stitchBuilds( ...@@ -366,22 +365,6 @@ export async function stitchBuilds(
)}` )}`
) )
// for server/font-manifest.json we just merge the arrays
for (const file of [AUTOMATIC_FONT_OPTIMIZATION_MANIFEST]) {
const [restoreFontManifest, currentFontManifest] = await Promise.all(
[
path.join(shuttleDir, 'server', file),
path.join(distDir, 'server', file),
].map(async (f) => JSON.parse(await fs.promises.readFile(f, 'utf8')))
)
const mergedFontManifest = [...restoreFontManifest, ...currentFontManifest]
await fs.promises.writeFile(
path.join(distDir, 'server', file),
JSON.stringify(mergedFontManifest, null, 2)
)
}
// for server/functions-config-manifest.json we just merge // for server/functions-config-manifest.json we just merge
// the functions field // the functions field
const [restoreFunctionsConfigManifest, currentFunctionsConfigManifest] = const [restoreFunctionsConfigManifest, currentFunctionsConfigManifest] =
......
...@@ -52,7 +52,6 @@ import { ...@@ -52,7 +52,6 @@ import {
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
EXPORT_DETAIL, EXPORT_DETAIL,
EXPORT_MARKER, EXPORT_MARKER,
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
IMAGES_MANIFEST, IMAGES_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
...@@ -2342,12 +2341,6 @@ export default async function build( ...@@ -2342,12 +2341,6 @@ export default async function build(
] ]
: []), : []),
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
config.optimizeFonts
? path.join(
SERVER_DIRECTORY,
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST
)
: null,
BUILD_ID_FILE, BUILD_ID_FILE,
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.js'), path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.js'),
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.json'), path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.json'),
...@@ -2469,10 +2462,6 @@ export default async function build( ...@@ -2469,10 +2462,6 @@ export default async function build(
featureName: 'experimental/nextScriptWorkers', featureName: 'experimental/nextScriptWorkers',
invocationCount: config.experimental.nextScriptWorkers ? 1 : 0, invocationCount: config.experimental.nextScriptWorkers ? 1 : 0,
}, },
{
featureName: 'optimizeFonts',
invocationCount: config.optimizeFonts ? 1 : 0,
},
{ {
featureName: 'experimental/ppr', featureName: 'experimental/ppr',
invocationCount: config.experimental.ppr ? 1 : 0, invocationCount: config.experimental.ppr ? 1 : 0,
......
...@@ -1856,20 +1856,6 @@ export default async function getBaseWebpackConfig( ...@@ -1856,20 +1856,6 @@ export default async function getBaseWebpackConfig(
clientRouterFilters, clientRouterFilters,
}), }),
new ProfilingPlugin({ runWebpackSpan, rootDir: dir }), new ProfilingPlugin({ runWebpackSpan, rootDir: dir }),
config.optimizeFonts &&
!dev &&
isNodeServer &&
(function () {
const { FontStylesheetGatheringPlugin } =
require('./webpack/plugins/font-stylesheet-gathering-plugin') as {
FontStylesheetGatheringPlugin: typeof import('./webpack/plugins/font-stylesheet-gathering-plugin').FontStylesheetGatheringPlugin
}
return new FontStylesheetGatheringPlugin({
adjustFontFallbacks: config.experimental.adjustFontFallbacks,
adjustFontFallbacksWithSizeAdjust:
config.experimental.adjustFontFallbacksWithSizeAdjust,
})
})(),
new WellKnownErrorsPlugin(), new WellKnownErrorsPlugin(),
isClient && isClient &&
new CopyFilePlugin({ new CopyFilePlugin({
...@@ -2071,7 +2057,6 @@ export default async function getBaseWebpackConfig( ...@@ -2071,7 +2057,6 @@ export default async function getBaseWebpackConfig(
buildActivityPosition: config.devIndicators.buildActivityPosition, buildActivityPosition: config.devIndicators.buildActivityPosition,
productionBrowserSourceMaps: !!config.productionBrowserSourceMaps, productionBrowserSourceMaps: !!config.productionBrowserSourceMaps,
reactStrictMode: config.reactStrictMode, reactStrictMode: config.reactStrictMode,
optimizeFonts: config.optimizeFonts,
optimizeCss: config.experimental.optimizeCss, optimizeCss: config.experimental.optimizeCss,
nextScriptWorkers: config.experimental.nextScriptWorkers, nextScriptWorkers: config.experimental.nextScriptWorkers,
scrollRestoration: config.experimental.scrollRestoration, scrollRestoration: config.experimental.scrollRestoration,
......
...@@ -235,7 +235,6 @@ export function getDefineEnv({ ...@@ -235,7 +235,6 @@ export function getDefineEnv({
'process.env.__NEXT_STRICT_MODE_APP': 'process.env.__NEXT_STRICT_MODE_APP':
// When next.config.js does not have reactStrictMode it's enabled by default. // When next.config.js does not have reactStrictMode it's enabled by default.
config.reactStrictMode === null ? true : config.reactStrictMode, config.reactStrictMode === null ? true : config.reactStrictMode,
'process.env.__NEXT_OPTIMIZE_FONTS': !dev && config.optimizeFonts,
'process.env.__NEXT_OPTIMIZE_CSS': 'process.env.__NEXT_OPTIMIZE_CSS':
(config.experimental.optimizeCss && !dev) ?? false, (config.experimental.optimizeCss && !dev) ?? false,
'process.env.__NEXT_SCRIPT_WORKERS': 'process.env.__NEXT_SCRIPT_WORKERS':
......
import {
webpack,
BasicEvaluatedExpression,
sources,
} from 'next/dist/compiled/webpack/webpack'
import {
getFontDefinitionFromNetwork,
getFontOverrideCss,
} from '../../../server/font-utils'
import type { FontManifest } from '../../../server/font-utils'
import postcss from 'postcss'
import minifier from 'next/dist/compiled/cssnano-simple'
import {
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
OPTIMIZED_FONT_PROVIDERS,
} from '../../../shared/lib/constants'
import * as Log from '../../output/log'
function minifyCss(css: string): Promise<string> {
return postcss([
minifier(
{
excludeAll: true,
discardComments: true,
normalizeWhitespace: { exclude: false },
},
postcss
),
])
.process(css, { from: undefined })
.then((res) => res.css)
}
function isNodeCreatingLinkElement(node: any) {
const callee = node.callee as any
if (callee.type !== 'Identifier') {
return false
}
const componentNode = node.arguments[0] as any
if (componentNode.type !== 'Literal') {
return false
}
// React has pragma: _jsx.
// Next has pragma: __jsx.
return (
(callee.name === '_jsx' || callee.name === '__jsx') &&
componentNode.value === 'link'
)
}
export class FontStylesheetGatheringPlugin {
compiler?: webpack.Compiler
gatheredStylesheets: Array<string> = []
manifestContent: FontManifest = []
adjustFontFallbacks?: boolean
adjustFontFallbacksWithSizeAdjust?: boolean
constructor({
adjustFontFallbacks,
adjustFontFallbacksWithSizeAdjust,
}: {
adjustFontFallbacks?: boolean
adjustFontFallbacksWithSizeAdjust?: boolean
}) {
this.adjustFontFallbacks = adjustFontFallbacks
this.adjustFontFallbacksWithSizeAdjust = adjustFontFallbacksWithSizeAdjust
}
private parserHandler = (
factory: ReturnType<webpack.Compiler['createNormalModuleFactory']>
): void => {
const JS_TYPES = ['auto', 'esm', 'dynamic']
// Do an extra walk per module and add interested visitors to the walk.
for (const type of JS_TYPES) {
factory.hooks.parser
.for('javascript/' + type)
.tap(this.constructor.name, (parser: any) => {
/**
* Webpack fun facts:
* `parser.hooks.call.for` cannot catch calls for user defined identifiers like `__jsx`
* it can only detect calls for native objects like `window`, `this`, `eval` etc.
* In order to be able to catch calls of variables like `__jsx`, first we need to catch them as
* Identifier and then return `BasicEvaluatedExpression` whose `id` and `type` webpack matches to
* invoke hook for call.
* See: https://github.com/webpack/webpack/blob/webpack-4/lib/Parser.js#L1931-L1932.
*/
parser.hooks.evaluate
.for('Identifier')
.tap(this.constructor.name, (node: any) => {
// We will only optimize fonts from first party code.
if (parser?.state?.module?.resource.includes('node_modules')) {
return
}
let result
if (node.name === '_jsx' || node.name === '__jsx') {
result = new BasicEvaluatedExpression()
// @ts-ignore
result.setRange(node.range)
result.setExpression(node)
result.setIdentifier(node.name)
// This was added in webpack 5.
result.getMembers = () => []
}
return result
})
const jsxNodeHandler = (node: any) => {
if (node.arguments.length !== 2) {
// A font link tag has only two arguments rel=stylesheet and href='...'
return
}
if (!isNodeCreatingLinkElement(node)) {
return
}
// node.arguments[0] is the name of the tag and [1] are the props.
const arg1 = node.arguments[1]
const propsNode =
arg1.type === 'ObjectExpression' ? (arg1 as any) : undefined
const props: { [key: string]: string } = {}
if (propsNode) {
propsNode.properties.forEach((prop: any) => {
if (prop.type !== 'Property') {
return
}
if (
prop.key.type === 'Identifier' &&
prop.value.type === 'Literal'
) {
props[prop.key.name] = prop.value.value as string
}
})
}
if (
!props.rel ||
props.rel !== 'stylesheet' ||
!props.href ||
!OPTIMIZED_FONT_PROVIDERS.some(({ url }) =>
props.href.startsWith(url)
)
) {
return false
}
this.gatheredStylesheets.push(props.href)
const buildInfo = parser?.state?.module?.buildInfo
if (buildInfo) {
buildInfo.valueDependencies.set(
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
this.gatheredStylesheets
)
}
}
// React JSX transform:
parser.hooks.call
.for('_jsx')
.tap(this.constructor.name, jsxNodeHandler)
// Next.js JSX transform:
parser.hooks.call
.for('__jsx')
.tap(this.constructor.name, jsxNodeHandler)
// New React JSX transform:
parser.hooks.call
.for('imported var')
.tap(this.constructor.name, jsxNodeHandler)
})
}
}
public apply(compiler: webpack.Compiler) {
this.compiler = compiler
compiler.hooks.normalModuleFactory.tap(
this.constructor.name,
this.parserHandler
)
compiler.hooks.make.tapAsync(this.constructor.name, (compilation, cb) => {
compilation.hooks.finishModules.tapAsync(
this.constructor.name,
async (modules: any, modulesFinished: Function) => {
let fontStylesheets = this.gatheredStylesheets
const fontUrls = new Set<string>()
modules.forEach((module: any) => {
const fontDependencies = module?.buildInfo?.valueDependencies?.get(
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST
)
if (fontDependencies) {
fontDependencies.forEach((v: string) => fontUrls.add(v))
}
})
fontStylesheets = Array.from(fontUrls)
const fontDefinitionPromises = fontStylesheets.map((url) =>
getFontDefinitionFromNetwork(url)
)
this.manifestContent = []
for (let promiseIndex in fontDefinitionPromises) {
let css = await fontDefinitionPromises[promiseIndex]
if (this.adjustFontFallbacks) {
css += getFontOverrideCss(
fontStylesheets[promiseIndex],
css,
this.adjustFontFallbacksWithSizeAdjust
)
}
if (css) {
try {
const content = await minifyCss(css)
this.manifestContent.push({
url: fontStylesheets[promiseIndex],
content,
})
} catch (err) {
Log.warn(
`Failed to minify the stylesheet for ${fontStylesheets[promiseIndex]}. Skipped optimizing this font.`
)
console.error(err)
}
}
}
// @ts-expect-error invalid assets type
compilation.assets[AUTOMATIC_FONT_OPTIMIZATION_MANIFEST] =
new sources.RawSource(
JSON.stringify(this.manifestContent, null, ' ')
)
modulesFinished()
}
)
cb()
})
compiler.hooks.make.tap(this.constructor.name, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: this.constructor.name,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
assets['../' + AUTOMATIC_FONT_OPTIMIZATION_MANIFEST] =
new sources.RawSource(
JSON.stringify(this.manifestContent, null, ' ')
)
}
)
})
}
}
...@@ -44,7 +44,6 @@ import { loadEnvConfig } from '@next/env' ...@@ -44,7 +44,6 @@ import { loadEnvConfig } from '@next/env'
import { isAPIRoute } from '../lib/is-api-route' import { isAPIRoute } from '../lib/is-api-route'
import { getPagePath } from '../server/require' import { getPagePath } from '../server/require'
import type { Span } from '../trace' import type { Span } from '../trace'
import type { FontConfig } from '../server/font-utils'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { isAppPageRoute } from '../lib/is-app-page-route' import { isAppPageRoute } from '../lib/is-app-page-route'
...@@ -340,7 +339,6 @@ async function exportAppImpl( ...@@ -340,7 +339,6 @@ async function exportAppImpl(
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output, nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers, nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes, largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverActions: nextConfig.experimental.serverActions, serverActions: nextConfig.experimental.serverActions,
serverComponents: enabledDirectories.app, serverComponents: enabledDirectories.app,
......
...@@ -87,16 +87,10 @@ export async function exportPagesPage( ...@@ -87,16 +87,10 @@ export async function exportPagesPage(
} }
} else { } else {
/** /**
* This sets environment variable to be used at the time of static export by head.tsx. * This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting SSR by calling * Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`. * `process.env.__NEXT_OPTIMIZE_CSS`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being cleaned up.
*/ */
if (renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(
renderOpts.optimizeFonts
)
}
if (renderOpts.optimizeCss) { if (renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
} }
......
...@@ -4,7 +4,6 @@ import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/rend ...@@ -4,7 +4,6 @@ import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/rend
import type { LoadComponentsReturnType } from '../server/load-components' import type { LoadComponentsReturnType } from '../server/load-components'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator' import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import type { FontConfig } from '../server/font-utils'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared' import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { Revalidate } from '../server/lib/revalidate' import type { Revalidate } from '../server/lib/revalidate'
import type { import type {
...@@ -70,7 +69,6 @@ export interface ExportPageInput { ...@@ -70,7 +69,6 @@ export interface ExportPageInput {
buildExport?: boolean buildExport?: boolean
serverRuntimeConfig: { [key: string]: any } serverRuntimeConfig: { [key: string]: any }
subFolders?: boolean subFolders?: boolean
optimizeFonts: FontConfig
optimizeCss: any optimizeCss: any
disableOptimizedLoading: any disableOptimizedLoading: any
parentSpanId: number parentSpanId: number
......
...@@ -18,7 +18,6 @@ import fs from 'fs/promises' ...@@ -18,7 +18,6 @@ import fs from 'fs/promises'
import { loadComponents } from '../server/load-components' import { loadComponents } from '../server/load-components'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { requireFontManifest } from '../server/require'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace' import { trace } from '../trace'
import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env' import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
...@@ -70,7 +69,6 @@ async function exportPageImpl( ...@@ -70,7 +69,6 @@ async function exportPageImpl(
buildExport = false, buildExport = false,
serverRuntimeConfig, serverRuntimeConfig,
subFolders = false, subFolders = false,
optimizeFonts,
optimizeCss, optimizeCss,
disableOptimizedLoading, disableOptimizedLoading,
debugOutput = false, debugOutput = false,
...@@ -252,10 +250,8 @@ async function exportPageImpl( ...@@ -252,10 +250,8 @@ async function exportPageImpl(
...input.renderOpts, ...input.renderOpts,
ampPath: renderAmpPath, ampPath: renderAmpPath,
params, params,
optimizeFonts,
optimizeCss, optimizeCss,
disableOptimizedLoading, disableOptimizedLoading,
fontManifest: optimizeFonts ? requireFontManifest(distDir) : undefined,
locale, locale,
supportsDynamicResponse: false, supportsDynamicResponse: false,
experimental: { experimental: {
...@@ -379,7 +375,6 @@ export async function exportPages( ...@@ -379,7 +375,6 @@ export async function exportPages(
serverRuntimeConfig: nextConfig.serverRuntimeConfig, serverRuntimeConfig: nextConfig.serverRuntimeConfig,
subFolders: nextConfig.trailingSlash && !options.buildExport, subFolders: nextConfig.trailingSlash && !options.buildExport,
buildExport: options.buildExport, buildExport: options.buildExport,
optimizeFonts: nextConfig.optimizeFonts,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading: disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading, nextConfig.experimental.disableOptimizedLoading,
......
...@@ -29,8 +29,6 @@ const unsupportedTurbopackNextConfigOptions = [ ...@@ -29,8 +29,6 @@ const unsupportedTurbopackNextConfigOptions = [
// 'experimental.serverMinification', // 'experimental.serverMinification',
// 'experimental.serverSourceMaps', // 'experimental.serverSourceMaps',
'experimental.adjustFontFallbacks',
'experimental.adjustFontFallbacksWithSizeAdjust',
'experimental.allowedRevalidateHeaderKeys', 'experimental.allowedRevalidateHeaderKeys',
'experimental.extensionAlias', 'experimental.extensionAlias',
'experimental.fallbackNodePolyfills', 'experimental.fallbackNodePolyfills',
......
import React, { type JSX } from 'react' import React, { type JSX } from 'react'
import type { ReactElement, ReactNode } from 'react' import { NEXT_BUILTIN_DOCUMENT } from '../shared/lib/constants'
import {
OPTIMIZED_FONT_PROVIDERS,
NEXT_BUILTIN_DOCUMENT,
} from '../shared/lib/constants'
import type { import type {
DocumentContext, DocumentContext,
DocumentInitialProps, DocumentInitialProps,
...@@ -433,7 +429,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -433,7 +429,6 @@ export class Head extends React.Component<HeadProps> {
dynamicImports, dynamicImports,
crossOrigin, crossOrigin,
optimizeCss, optimizeCss,
optimizeFonts,
} = this.context } = this.context
const cssFiles = files.allFiles.filter((f) => f.endsWith('.css')) const cssFiles = files.allFiles.filter((f) => f.endsWith('.css'))
const sharedFiles: Set<string> = new Set(files.sharedFiles) const sharedFiles: Set<string> = new Set(files.sharedFiles)
...@@ -488,12 +483,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -488,12 +483,6 @@ export class Head extends React.Component<HeadProps> {
) )
}) })
if (process.env.NODE_ENV !== 'development' && optimizeFonts) {
cssLinkElements = this.makeStylesheetInert(
cssLinkElements
) as ReactElement[]
}
return cssLinkElements.length === 0 ? null : cssLinkElements return cssLinkElements.length === 0 ? null : cssLinkElements
} }
...@@ -623,36 +612,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -623,36 +612,6 @@ export class Head extends React.Component<HeadProps> {
return getPolyfillScripts(this.context, this.props) return getPolyfillScripts(this.context, this.props)
} }
makeStylesheetInert(node: ReactNode[]): ReactNode[] {
return React.Children.map(node, (c: any) => {
if (
c?.type === 'link' &&
c?.props?.href &&
OPTIMIZED_FONT_PROVIDERS.some(({ url }) =>
c?.props?.href?.startsWith(url)
)
) {
const newProps = {
...(c.props || {}),
'data-href': c.props.href,
href: undefined,
}
return React.cloneElement(c, newProps)
} else if (c?.props?.children) {
const newProps = {
...(c.props || {}),
children: this.makeStylesheetInert(c.props.children),
}
return React.cloneElement(c, newProps)
}
return c
// @types/react bug. Returned value from .map will not be `null` if you pass in `[null]`
})!.filter(Boolean)
}
render() { render() {
const { const {
styles, styles,
...@@ -667,7 +626,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -667,7 +626,6 @@ export class Head extends React.Component<HeadProps> {
unstable_JsPreload, unstable_JsPreload,
disableOptimizedLoading, disableOptimizedLoading,
optimizeCss, optimizeCss,
optimizeFonts,
assetPrefix, assetPrefix,
nextFontManifest, nextFontManifest,
} = this.context } = this.context
...@@ -740,14 +698,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -740,14 +698,6 @@ export class Head extends React.Component<HeadProps> {
) )
} }
if (
process.env.NODE_ENV !== 'development' &&
optimizeFonts &&
!(process.env.NEXT_RUNTIME !== 'edge' && inAmpMode)
) {
children = this.makeStylesheetInert(children)
}
let hasAmphtmlRel = false let hasAmphtmlRel = false
let hasCanonicalRel = false let hasCanonicalRel = false
...@@ -848,7 +798,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -848,7 +798,6 @@ export class Head extends React.Component<HeadProps> {
)} )}
{children} {children}
{optimizeFonts && <meta name="next-font-preconnect" />}
{nextFontLinkTags.preconnect} {nextFontLinkTags.preconnect}
{nextFontLinkTags.preload} {nextFontLinkTags.preload}
......
import type { __ApiPreviewProps } from './api-utils' import type { __ApiPreviewProps } from './api-utils'
import type { FontManifest, FontConfig } from './font-utils'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher' import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from '../client/components/params' import type { Params } from '../client/components/params'
...@@ -370,7 +369,6 @@ export default abstract class Server< ...@@ -370,7 +369,6 @@ export default abstract class Server<
shouldEnsure?: boolean shouldEnsure?: boolean
url?: string url?: string
}): Promise<FindComponentsResult | null> }): Promise<FindComponentsResult | null>
protected abstract getFontManifest(): DeepReadonly<FontManifest> | undefined
protected abstract getPrerenderManifest(): DeepReadonly<PrerenderManifest> protected abstract getPrerenderManifest(): DeepReadonly<PrerenderManifest>
protected abstract getNextFontManifest(): protected abstract getNextFontManifest():
| DeepReadonly<NextFontManifest> | DeepReadonly<NextFontManifest>
...@@ -560,11 +558,6 @@ export default abstract class Server< ...@@ -560,11 +558,6 @@ export default abstract class Server<
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer, ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
images: this.nextConfig.images, images: this.nextConfig.images,
optimizeFonts: this.nextConfig.optimizeFonts as FontConfig,
fontManifest:
(this.nextConfig.optimizeFonts as FontConfig) && !dev
? this.getFontManifest()
: undefined,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
nextConfigOutput: this.nextConfig.output, nextConfigOutput: this.nextConfig.output,
nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers, nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,
......
...@@ -254,8 +254,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -254,8 +254,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
appIsrStatus: z.boolean().optional(), appIsrStatus: z.boolean().optional(),
appNavFailHandling: z.boolean().optional(), appNavFailHandling: z.boolean().optional(),
preloadEntriesOnStart: z.boolean().optional(), preloadEntriesOnStart: z.boolean().optional(),
adjustFontFallbacks: z.boolean().optional(),
adjustFontFallbacksWithSizeAdjust: z.boolean().optional(),
allowedRevalidateHeaderKeys: z.array(z.string()).optional(), allowedRevalidateHeaderKeys: z.array(z.string()).optional(),
amp: z amp: z
.object({ .object({
...@@ -563,7 +561,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -563,7 +561,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
pagesBufferLength: z.number().optional(), pagesBufferLength: z.number().optional(),
}) })
.optional(), .optional(),
optimizeFonts: z.boolean().optional(),
output: z.enum(['standalone', 'export']).optional(), output: z.enum(['standalone', 'export']).optional(),
outputFileTracingRoot: z.string().optional(), outputFileTracingRoot: z.string().optional(),
outputFileTracingExcludes: z outputFileTracingExcludes: z
......
...@@ -298,8 +298,6 @@ export interface ExperimentalConfig { ...@@ -298,8 +298,6 @@ export interface ExperimentalConfig {
sri?: { sri?: {
algorithm?: SubresourceIntegrityAlgorithm algorithm?: SubresourceIntegrityAlgorithm
} }
adjustFontFallbacks?: boolean
adjustFontFallbacksWithSizeAdjust?: boolean
webVitalsAttribution?: Array<(typeof WEB_VITALS)[number]> webVitalsAttribution?: Array<(typeof WEB_VITALS)[number]>
...@@ -750,15 +748,6 @@ export interface NextConfig extends Record<string, any> { ...@@ -750,15 +748,6 @@ export interface NextConfig extends Record<string, any> {
*/ */
productionBrowserSourceMaps?: boolean productionBrowserSourceMaps?: boolean
/**
* By default, Next.js will automatically inline font CSS at build time
*
* @default true
* @since version 10.2
* @see [Font Optimization](https://nextjs.org/docs/basic-features/font-optimization)
*/
optimizeFonts?: boolean
/** /**
* Enable react profiling in production * Enable react profiling in production
* *
...@@ -963,7 +952,6 @@ export const defaultConfig: NextConfig = { ...@@ -963,7 +952,6 @@ export const defaultConfig: NextConfig = {
trailingSlash: false, trailingSlash: false,
i18n: null, i18n: null,
productionBrowserSourceMaps: false, productionBrowserSourceMaps: false,
optimizeFonts: true,
excludeDefaultMomentLocales: true, excludeDefaultMomentLocales: true,
serverRuntimeConfig: {}, serverRuntimeConfig: {},
publicRuntimeConfig: {}, publicRuntimeConfig: {},
...@@ -1025,8 +1013,6 @@ export const defaultConfig: NextConfig = { ...@@ -1025,8 +1013,6 @@ export const defaultConfig: NextConfig = {
disablePostcssPresetEnv: undefined, disablePostcssPresetEnv: undefined,
amp: undefined, amp: undefined,
urlImports: undefined, urlImports: undefined,
adjustFontFallbacks: false,
adjustFontFallbacksWithSizeAdjust: false,
turbo: undefined, turbo: undefined,
turbotrace: undefined, turbotrace: undefined,
typedRoutes: false, typedRoutes: false,
......
...@@ -12,7 +12,6 @@ import type { LoadableManifest } from '../../load-components' ...@@ -12,7 +12,6 @@ import type { LoadableManifest } from '../../load-components'
import { import {
APP_BUILD_MANIFEST, APP_BUILD_MANIFEST,
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
BUILD_MANIFEST, BUILD_MANIFEST,
INTERCEPTION_ROUTE_REWRITE_MANIFEST, INTERCEPTION_ROUTE_REWRITE_MANIFEST,
MIDDLEWARE_BUILD_MANIFEST, MIDDLEWARE_BUILD_MANIFEST,
...@@ -267,18 +266,6 @@ export class TurbopackManifestLoader { ...@@ -267,18 +266,6 @@ export class TurbopackManifestLoader {
) )
} }
/**
* Turbopack doesn't support this functionality, so it writes an empty manifest.
*/
private async writeAutomaticFontOptimizationManifest() {
const manifestPath = join(
this.distDir,
'server',
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST
)
await writeFileAtomic(manifestPath, JSON.stringify([]))
}
async loadBuildManifest( async loadBuildManifest(
pageName: string, pageName: string,
...@@ -664,7 +651,6 @@ export class TurbopackManifestLoader { ...@@ -664,7 +651,6 @@ export class TurbopackManifestLoader {
await this.writeActionManifest() await this.writeActionManifest()
await this.writeAppBuildManifest() await this.writeAppBuildManifest()
await this.writeAppPathsManifest() await this.writeAppPathsManifest()
await this.writeAutomaticFontOptimizationManifest()
await this.writeBuildManifest(entrypoints, devRewrites, productionRewrites) await this.writeBuildManifest(entrypoints, devRewrites, productionRewrites)
await this.writeFallbackBuildManifest() await this.writeFallbackBuildManifest()
await this.writeLoadableManifest() await this.writeLoadableManifest()
......
import * as Log from '../build/output/log'
import { import {
GOOGLE_FONT_PROVIDER,
DEFAULT_SERIF_FONT, DEFAULT_SERIF_FONT,
DEFAULT_SANS_SERIF_FONT, DEFAULT_SANS_SERIF_FONT,
} from '../shared/lib/constants' } from '../shared/lib/constants'
const capsizeFontsMetrics = require('next/dist/server/capsize-font-metrics.json') const capsizeFontsMetrics = require('next/dist/server/capsize-font-metrics.json')
const CHROME_UA =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
const IE_UA = 'Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko'
export type FontManifest = Array<{
url: string
content: string
}>
export type FontConfig = boolean
function isGoogleFont(url: string): boolean {
return url.startsWith(GOOGLE_FONT_PROVIDER)
}
async function getFontForUA(url: string, UA: string): Promise<string> {
const res = await fetch(url, { headers: { 'user-agent': UA } })
return await res.text()
}
export async function getFontDefinitionFromNetwork(
url: string
): Promise<string> {
let result = ''
/**
* The order of IE -> Chrome is important, other wise chrome starts loading woff1.
* CSS cascading 🤷‍♂️.
*/
try {
if (isGoogleFont(url)) {
result += await getFontForUA(url, IE_UA)
}
result += await getFontForUA(url, CHROME_UA)
} catch (e) {
Log.warn(
`Failed to download the stylesheet for ${url}. Skipped optimizing this font.`
)
return ''
}
return result
}
function parseGoogleFontName(css: string): Array<string> {
const regex = /font-family: ([^;]*)/g
const matches = css.matchAll(regex)
const fontNames = new Set<string>()
for (let font of matches) {
const fontFamily = font[1].replace(/^['"]|['"]$/g, '')
fontNames.add(fontFamily)
}
return [...fontNames]
}
function formatName(str: string): string { function formatName(str: string): string {
return str return str
.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) { .replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
...@@ -74,24 +16,6 @@ function formatOverrideValue(val: number) { ...@@ -74,24 +16,6 @@ function formatOverrideValue(val: number) {
return Math.abs(val * 100).toFixed(2) return Math.abs(val * 100).toFixed(2)
} }
export function calculateOverrideValues(fontName: string) {
const fontKey = formatName(fontName)
const fontMetrics = capsizeFontsMetrics[fontKey]
let { category, ascent, descent, lineGap, unitsPerEm } = fontMetrics
const fallbackFont =
category === 'serif' ? DEFAULT_SERIF_FONT : DEFAULT_SANS_SERIF_FONT
ascent = formatOverrideValue(ascent / unitsPerEm)
descent = formatOverrideValue(descent / unitsPerEm)
lineGap = formatOverrideValue(lineGap / unitsPerEm)
return {
ascent,
descent,
lineGap,
fallbackFont: fallbackFont.name,
}
}
export function calculateSizeAdjustValues(fontName: string) { export function calculateSizeAdjustValues(fontName: string) {
const fontKey = formatName(fontName) const fontKey = formatName(fontName)
const fontMetrics = capsizeFontsMetrics[fontKey] const fontMetrics = capsizeFontsMetrics[fontKey]
...@@ -118,64 +42,3 @@ export function calculateSizeAdjustValues(fontName: string) { ...@@ -118,64 +42,3 @@ export function calculateSizeAdjustValues(fontName: string) {
sizeAdjust: formatOverrideValue(sizeAdjust), sizeAdjust: formatOverrideValue(sizeAdjust),
} }
} }
function calculateOverrideCSS(font: string) {
const fontName = font.trim()
const { ascent, descent, lineGap, fallbackFont } =
calculateOverrideValues(fontName)
return `
@font-face {
font-family: "${fontName} Fallback";
ascent-override: ${ascent}%;
descent-override: ${descent}%;
line-gap-override: ${lineGap}%;
src: local("${fallbackFont}");
}
`
}
function calculateSizeAdjustCSS(font: string) {
const fontName = font.trim()
const { ascent, descent, lineGap, fallbackFont, sizeAdjust } =
calculateSizeAdjustValues(fontName)
return `
@font-face {
font-family: "${fontName} Fallback";
ascent-override: ${ascent}%;
descent-override: ${descent}%;
line-gap-override: ${lineGap}%;
size-adjust: ${sizeAdjust}%;
src: local("${fallbackFont}");
}
`
}
export function getFontOverrideCss(
url: string,
css: string,
useSizeAdjust = false
) {
if (!isGoogleFont(url)) {
return ''
}
const calcFn = useSizeAdjust ? calculateSizeAdjustCSS : calculateOverrideCSS
try {
const fontNames = parseGoogleFontName(css)
const fontCss = fontNames.reduce((cssStr, fontName) => {
cssStr += calcFn(fontName)
return cssStr
}, '')
return fontCss
} catch (e) {
console.log('Error getting font override values - ', e)
return ''
}
}
...@@ -59,13 +59,12 @@ import type { ...@@ -59,13 +59,12 @@ import type {
BaseRequestHandler, BaseRequestHandler,
} from './base-server' } from './base-server'
import BaseServer, { NoFallbackError } from './base-server' import BaseServer, { NoFallbackError } from './base-server'
import { getMaybePagePath, getPagePath, requireFontManifest } from './require' import { getMaybePagePath, getPagePath } from './require'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { loadComponents } from './load-components' import { loadComponents } from './load-components'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import isError, { getProperError } from '../lib/is-error' import isError, { getProperError } from '../lib/is-error'
import type { FontManifest } from './font-utils'
import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils' import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
...@@ -178,11 +177,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -178,11 +177,6 @@ export default class NextNodeServer extends BaseServer<
* Using this from process.env allows targeting SSR by calling * Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_CSS`. * `process.env.__NEXT_OPTIMIZE_CSS`.
*/ */
if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(
this.renderOpts.optimizeFonts
)
}
if (this.renderOpts.optimizeCss) { if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
} }
...@@ -784,10 +778,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -784,10 +778,6 @@ export default class NextNodeServer extends BaseServer<
return null return null
} }
protected getFontManifest(): FontManifest {
return requireFontManifest(this.distDir)
}
protected getNextFontManifest(): NextFontManifest | undefined { protected getNextFontManifest(): NextFontManifest | undefined {
return loadManifest( return loadManifest(
join(this.distDir, 'server', NEXT_FONT_MANIFEST + '.json') join(this.distDir, 'server', NEXT_FONT_MANIFEST + '.json')
......
import type { RenderOpts } from './render' import type { RenderOpts } from './render'
import type { HTMLElement } from 'next/dist/compiled/node-html-parser'
import { OPTIMIZED_FONT_PROVIDERS } from '../shared/lib/constants'
import { nonNullable } from '../lib/non-nullable' import { nonNullable } from '../lib/non-nullable'
type postProcessOptions = {
optimizeFonts: any
}
type renderOptions = {
getFontDefinition?: (url: string) => string
}
interface PostProcessMiddleware {
inspect: (originalDom: HTMLElement, options: renderOptions) => any
mutate: (markup: string, data: any, options: renderOptions) => Promise<string>
}
type middlewareSignature = {
name: string
middleware: PostProcessMiddleware
condition: ((options: postProcessOptions) => boolean) | null
}
type PostProcessorFunction = type PostProcessorFunction =
| ((html: string) => Promise<string>) | ((html: string) => Promise<string>)
| ((html: string) => string) | ((html: string) => string)
const middlewareRegistry: Array<middlewareSignature> = []
function registerPostProcessor(
name: string,
middleware: PostProcessMiddleware,
condition?: (options: postProcessOptions) => boolean
) {
middlewareRegistry.push({ name, middleware, condition: condition || null })
}
async function processHTML(
html: string,
data: renderOptions,
options: postProcessOptions
): Promise<string> {
// Don't parse unless there's at least one processor middleware
if (!middlewareRegistry[0]) {
return html
}
const { parse } =
require('next/dist/compiled/node-html-parser') as typeof import('next/dist/compiled/node-html-parser')
const root: HTMLElement = parse(html)
let document = html
// Calls the middleware, with some instrumentation and logging
async function callMiddleWare(middleware: PostProcessMiddleware) {
// let timer = Date.now()
const inspectData = middleware.inspect(root, data)
document = await middleware.mutate(document, inspectData, data)
// timer = Date.now() - timer
// if (timer > MIDDLEWARE_TIME_BUDGET) {
// TODO: Identify a correct upper limit for the postprocess step
// and add a warning to disable the optimization
// }
return
}
for (let i = 0; i < middlewareRegistry.length; i++) {
let middleware = middlewareRegistry[i]
if (!middleware.condition || middleware.condition(options)) {
await callMiddleWare(middlewareRegistry[i].middleware)
}
}
return document
}
class FontOptimizerMiddleware implements PostProcessMiddleware {
inspect(originalDom: HTMLElement, options: renderOptions) {
if (!options.getFontDefinition) {
return
}
const fontDefinitions: (string | undefined)[][] = []
// collecting all the requested font definitions
originalDom
.querySelectorAll('link')
.filter(
(tag: HTMLElement) =>
tag.getAttribute('rel') === 'stylesheet' &&
tag.hasAttribute('data-href') &&
OPTIMIZED_FONT_PROVIDERS.some(({ url }) => {
const dataHref = tag.getAttribute('data-href')
return dataHref ? dataHref.startsWith(url) : false
})
)
.forEach((element: HTMLElement) => {
const url = element.getAttribute('data-href')
const nonce = element.getAttribute('nonce')
if (url) {
fontDefinitions.push([url, nonce])
}
})
return fontDefinitions
}
mutate = async (
markup: string,
fontDefinitions: string[][],
options: renderOptions
) => {
let result = markup
let preconnectUrls = new Set<string>()
if (!options.getFontDefinition) {
return markup
}
fontDefinitions.forEach((fontDef) => {
const [url, nonce] = fontDef
const fallBackLinkTag = `<link rel="stylesheet" href="${url}"/>`
if (
result.indexOf(`<style data-href="${url}">`) > -1 ||
result.indexOf(fallBackLinkTag) > -1
) {
// The font is already optimized and probably the response is cached
return
}
const fontContent = options.getFontDefinition
? options.getFontDefinition(url as string)
: null
if (!fontContent) {
/**
* In case of unreachable font definitions, fallback to default link tag.
*/
result = result.replace('</head>', `${fallBackLinkTag}</head>`)
} else {
const nonceStr = nonce ? ` nonce="${nonce}"` : ''
let dataAttr = ''
if (fontContent.includes('ascent-override')) {
dataAttr = ' data-size-adjust="true"'
}
result = result.replace(
'</head>',
`<style data-href="${url}"${nonceStr}${dataAttr}>${fontContent}</style></head>`
)
// Remove inert font tag
const escapedUrl = url
.replace(/&/g, '&amp;')
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const fontRegex = new RegExp(
`<link[^>]*data-href="${escapedUrl}"[^>]*/>`
)
result = result.replace(fontRegex, '')
const provider = OPTIMIZED_FONT_PROVIDERS.find((p) =>
url.startsWith(p.url)
)
if (provider) {
preconnectUrls.add(provider.preconnect)
}
}
})
let preconnectTag = ''
preconnectUrls.forEach((url) => {
preconnectTag += `<link rel="preconnect" href="${url}" crossorigin />`
})
result = result.replace(
'<meta name="next-font-preconnect"/>',
preconnectTag
)
return result
}
}
async function postProcessHTML( async function postProcessHTML(
pathname: string, pathname: string,
content: string, content: string,
...@@ -187,8 +14,6 @@ async function postProcessHTML( ...@@ -187,8 +14,6 @@ async function postProcessHTML(
| 'ampOptimizerConfig' | 'ampOptimizerConfig'
| 'ampValidator' | 'ampValidator'
| 'ampSkipValidation' | 'ampSkipValidation'
| 'optimizeFonts'
| 'fontManifest'
| 'optimizeCss' | 'optimizeCss'
| 'distDir' | 'distDir'
| 'assetPrefix' | 'assetPrefix'
...@@ -207,30 +32,6 @@ async function postProcessHTML( ...@@ -207,30 +32,6 @@ async function postProcessHTML(
return html return html
} }
: null, : null,
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeFonts
? async (html: string) => {
const getFontDefinition = (url: string) => {
if (!renderOpts.fontManifest) {
return ''
}
return (
renderOpts.fontManifest.find((font) => {
if (font && font.url === url) {
return true
}
return false
})?.content || ''
)
}
return await processHTML(
html,
{ getFontDefinition },
{
optimizeFonts: renderOpts.optimizeFonts,
}
)
}
: null,
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss
? async (html: string) => { ? async (html: string) => {
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
...@@ -265,13 +66,4 @@ async function postProcessHTML( ...@@ -265,13 +66,4 @@ async function postProcessHTML(
return content return content
} }
// Initialization
registerPostProcessor(
'Inline-Fonts',
new FontOptimizerMiddleware(),
// Using process.env because passing Experimental flag through loader is not possible.
// @ts-ignore
(options) => options.optimizeFonts || process.env.__NEXT_OPTIMIZE_FONTS
)
export { postProcessHTML } export { postProcessHTML }
...@@ -21,7 +21,6 @@ import { ...@@ -21,7 +21,6 @@ import {
setLazyProp, setLazyProp,
} from './api-utils' } from './api-utils'
import { getCookieParser } from './api-utils/get-cookie-parser' import { getCookieParser } from './api-utils/get-cookie-parser'
import type { FontManifest, FontConfig } from './font-utils'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import type { import type {
GetServerSideProps, GetServerSideProps,
...@@ -252,8 +251,6 @@ export type RenderOptsPartial = { ...@@ -252,8 +251,6 @@ export type RenderOptsPartial = {
basePath: string basePath: string
unstable_runtimeJS?: false unstable_runtimeJS?: false
unstable_JsPreload?: false unstable_JsPreload?: false
optimizeFonts: FontConfig
fontManifest?: DeepReadonly<FontManifest>
optimizeCss: any optimizeCss: any
nextConfigOutput?: 'standalone' | 'export' nextConfigOutput?: 'standalone' | 'export'
nextScriptWorkers: any nextScriptWorkers: any
...@@ -1491,7 +1488,6 @@ export async function renderToHTMLImpl( ...@@ -1491,7 +1488,6 @@ export async function renderToHTMLImpl(
styles: documentResult.styles, styles: documentResult.styles,
crossOrigin: renderOpts.crossOrigin, crossOrigin: renderOpts.crossOrigin,
optimizeCss: renderOpts.optimizeCss, optimizeCss: renderOpts.optimizeCss,
optimizeFonts: renderOpts.optimizeFonts,
nextConfigOutput: renderOpts.nextConfigOutput, nextConfigOutput: renderOpts.nextConfigOutput,
nextScriptWorkers: renderOpts.nextScriptWorkers, nextScriptWorkers: renderOpts.nextScriptWorkers,
runtime: globalRuntime, runtime: globalRuntime,
......
import path from 'path' import path from 'path'
import { import {
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
...@@ -13,7 +12,6 @@ import { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils' ...@@ -13,7 +12,6 @@ import { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils'
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import { loadManifest } from './load-manifest' import { loadManifest } from './load-manifest'
import { promises } from 'fs' import { promises } from 'fs'
import type { FontManifest } from './font-utils'
const isDev = process.env.NODE_ENV === 'development' const isDev = process.env.NODE_ENV === 'development'
const pagePathCache = !isDev const pagePathCache = !isDev
...@@ -130,11 +128,3 @@ export async function requirePage( ...@@ -130,11 +128,3 @@ export async function requirePage(
process.env.__NEXT_PRIVATE_RUNTIME_TYPE = '' process.env.__NEXT_PRIVATE_RUNTIME_TYPE = ''
} }
} }
export function requireFontManifest(distDir: string) {
const serverBuildPath = path.join(distDir, SERVER_DIRECTORY)
const fontManifest = loadManifest(
path.join(serverBuildPath, AUTOMATIC_FONT_OPTIMIZATION_MANIFEST)
) as FontManifest
return fontManifest
}
...@@ -48,7 +48,6 @@ export const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST = ...@@ -48,7 +48,6 @@ export const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST =
'_clientMiddlewareManifest.json' '_clientMiddlewareManifest.json'
export const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json' export const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json' export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
export const AUTOMATIC_FONT_OPTIMIZATION_MANIFEST = 'font-manifest.json'
export const SERVER_DIRECTORY = 'server' export const SERVER_DIRECTORY = 'server'
export const CONFIG_FILES = [ export const CONFIG_FILES = [
'next.config.js', 'next.config.js',
...@@ -96,11 +95,6 @@ export const DEFAULT_RUNTIME_WEBPACK = 'webpack-runtime' ...@@ -96,11 +95,6 @@ export const DEFAULT_RUNTIME_WEBPACK = 'webpack-runtime'
export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack' export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'
export const STATIC_PROPS_ID = '__N_SSG' export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP' export const SERVER_PROPS_ID = '__N_SSP'
export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/'
export const OPTIMIZED_FONT_PROVIDERS = [
{ url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' },
{ url: 'https://use.typekit.net', preconnect: 'https://use.typekit.net' },
]
export const DEFAULT_SERIF_FONT = { export const DEFAULT_SERIF_FONT = {
name: 'Times New Roman', name: 'Times New Roman',
xAvgCharWidth: 821, xAvgCharWidth: 821,
......
import type { BuildManifest } from '../../server/get-page-files' import type { BuildManifest } from '../../server/get-page-files'
import type { ServerRuntime } from '../../types' import type { ServerRuntime } from '../../types'
import type { NEXT_DATA } from './utils' import type { NEXT_DATA } from './utils'
import type { FontConfig } from '../../server/font-utils'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { DeepReadonly } from './deep-readonly' import type { DeepReadonly } from './deep-readonly'
...@@ -40,7 +39,6 @@ export type HtmlProps = { ...@@ -40,7 +39,6 @@ export type HtmlProps = {
head?: Array<JSX.Element | null> head?: Array<JSX.Element | null>
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
optimizeCss?: any optimizeCss?: any
optimizeFonts?: FontConfig
nextConfigOutput?: 'standalone' | 'export' nextConfigOutput?: 'standalone' | 'export'
nextScriptWorkers?: boolean nextScriptWorkers?: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
......
...@@ -155,7 +155,6 @@ export type EventBuildFeatureUsage = { ...@@ -155,7 +155,6 @@ export type EventBuildFeatureUsage = {
| 'experimental/nextScriptWorkers' | 'experimental/nextScriptWorkers'
| 'experimental/optimizeCss' | 'experimental/optimizeCss'
| 'experimental/ppr' | 'experimental/ppr'
| 'optimizeFonts'
| 'swcLoader' | 'swcLoader'
| 'swcRelay' | 'swcRelay'
| 'swcStyledComponents' | 'swcStyledComponents'
......
module.exports = {
cleanDistDir: false,
experimental: {
adjustFontFallbacks: true,
adjustFontFallbacksWithSizeAdjust: true,
},
}
import '../styles/styles.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
import * as React from 'react'
import Document, { Main, NextScript, Head, Html } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Open+Sans&family=Libre+Baskerville&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import React from 'react'
const Page = () => {
return <div>Hello!</div>
}
export default Page
module.exports = {
cleanDistDir: false,
experimental: {
adjustFontFallbacks: true,
},
}
import '../styles/styles.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
import * as React from 'react'
import Document, { Main, NextScript, Head, Html } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Open+Sans&family=Libre+Baskerville&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import React from 'react'
const Page = () => {
return <div>Hello!</div>
}
export default Page
import React from 'react'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
const Page = () => {
return <div className={inter.className}>Hello</div>
}
export default Page
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html>
<Head>
<>
{false && <script data-href="test"></script>}
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin
/>
<link
href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap"
rel="stylesheet"
/>
</>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
export default function Home() {
return (
<h1>
Falsey values contained in an element contained in Head should not result
in an error!
</h1>
)
}
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
const things = { className: 'test' }
return (
<Html>
<Head />
<link {...things} />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
[
{
"url": "https://fonts.googleapis.com/css2?family=Modak",
"content": "@font-face{font-family:'Modak';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/modak/v18/EJRYQgs1XtIEsnME.woff) format('woff')}@font-face{font-family:'Modak';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/modak/v18/EJRYQgs1XtIEskMB-hR77LKVTy8.woff2) format('woff2');unicode-range:U+0900-097F,U+1CD0-1CF6,U+1CF8-1CF9,U+200C-200D,U+20A8,U+20B9,U+25CC,U+A830-A839,U+A8E0-A8FB}@font-face{font-family:'Modak';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/modak/v18/EJRYQgs1XtIEskMO-hR77LKVTy8.woff2) format('woff2');unicode-range:U+0100-024F,U+0259,U+1E00-1EFF,U+2020,U+20A0-20AB,U+20AD-20CF,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:'Modak';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/modak/v18/EJRYQgs1XtIEskMA-hR77LKV.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}"
},
{
"url": "https://fonts.googleapis.com/css?family=Voces",
"content": "@font-face{font-family:'Voces';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/voces/v20/-F6_fjJyLyU8d7PGDmk.woff) format('woff')}@font-face{font-family:'Voces';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/voces/v20/-F6_fjJyLyU8d7PIDm_6pClI_ik.woff2) format('woff2');unicode-range:U+0100-024F,U+0259,U+1E00-1EFF,U+2020,U+20A0-20AB,U+20AD-20CF,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:'Voces';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/voces/v20/-F6_fjJyLyU8d7PGDm_6pClI.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}"
},
{
"url": "https://fonts.googleapis.com/css2?family=Roboto:wght@700",
"content": "@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlvAA.woff) format('woff')}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCRc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0460-052F,U+1C80-1C88,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfABc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCBc4AMP6lbBP.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBxc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCxc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EF9,U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfChc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0100-024F,U+0259,U+1E00-1EFF,U+2020,U+20A0-20AB,U+20AD-20CF,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4AMP6lQ.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}"
},
{
"url": "https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&display=swap",
"content": "@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Me5g.woff) format('woff')}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlvAA.woff) format('woff')}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtvAA.woff) format('woff')}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu72xKKTU1Kvnz.woff2) format('woff2');unicode-range:U+0460-052F,U+1C80-1C88,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu5mxKKTU1Kvnz.woff2) format('woff2');unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7mxKKTU1Kvnz.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4WxKKTU1Kvnz.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7WxKKTU1Kvnz.woff2) format('woff2');unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EF9,U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu7GxKKTU1Kvnz.woff2) format('woff2');unicode-range:U+0100-024F,U+0259,U+1E00-1EFF,U+2020,U+20A0-20AB,U+20AD-20CF,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCRc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0460-052F,U+1C80-1C88,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfABc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCBc4AMP6lbBP.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBxc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfCxc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EF9,U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfChc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0100-024F,U+0259,U+1E00-1EFF,U+2020,U+20A0-20AB,U+20AD-20CF,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4AMP6lQ.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfCRc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0460-052F,U+1C80-1C88,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfABc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfCBc4AMP6lbBP.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBxc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfCxc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+1EA0-1EF9,U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfChc4AMP6lbBP.woff2) format('woff2');unicode-range:U+0100-024F,U+0259,U+1E00-1EFF,U+2020,U+20A0-20AB,U+20AD-20CF,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;font-display:swap;src:url(https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBBc4AMP6lQ.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}"
}
]
module.exports = {
cleanDistDir: false,
experimental: {
amp: {
validator: require.resolve('../../../../lib/amp-validator-wasm.js'),
},
},
}
import * as React from 'react'
import Document, { Main, NextScript, Head, Html } from 'next/document'
export default class MyDocument extends Document {
constructor(props) {
super(props)
const { __NEXT_DATA__, ids } = props
if (ids) {
__NEXT_DATA__.ids = ids
}
}
render() {
return (
<Html>
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Voces"
/>
{false && <script data-href="test"></script>}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import React from 'react'
const Page = () => {
return <div>Hi!</div>
}
export const config = { amp: true }
export default Page
import React from 'react'
import Link from 'next/link'
const Page = () => {
return (
<div>
Hi!
<br />
<br />
<Link href="/with-font" id="with-font">
With font
</Link>
</div>
)
}
export default Page
import React from 'react'
import Head from 'next/head'
const Page = () => {
return (
<>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Modak"
rel="stylesheet"
nonce="VmVyY2Vs"
/>
</Head>
<div>Hi!</div>
</>
)
}
export default Page
import Head from 'next/head'
function Home({ stars }) {
return (
<div className="container">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@700"
></link>
</Head>
<main>
<div>Next stars: {stars}</div>
</main>
</div>
)
}
Home.getInitialProps = async () => {
return { stars: Math.random() * 1000 }
}
export default Home
import React from 'react'
import Head from 'next/head'
const Page = () => {
return (
<>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Modak"
rel="stylesheet"
/>
</Head>
<div>Hi!</div>
</>
)
}
export default Page
import Head from 'next/head'
import Link from 'next/link'
const WithFont = () => {
return (
<>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&display=swap"
rel="stylesheet"
/>
</Head>
<div id="with-font-container">
Page with custom fonts
<br />
<br />
<Link href="/without-font">Without font</Link>
</div>
</>
)
}
export const getServerSideProps = async () => {
return {
props: {},
}
}
export default WithFont
import Head from 'next/head'
import Link from 'next/link'
const WithoutFont = () => {
return (
<>
<Head>
<meta name="robots" content="noindex, nofollow" />
</Head>
<div>
Page without custom fonts
<br />
<br />
<Link href="/with-font">With font</Link>
</div>
</>
)
}
export const getServerSideProps = async () => {
return {
props: {},
}
}
export default WithoutFont
[
{
"url": "https://use.typekit.net/plm1izr.css",
"content": "@import url(\"https://p.typekit.net/p.css?s=1&k=plm1izr&ht=tk&f=32266&a=23152309&app=typekit&e=css\");@font-face{font-family:\"birra-2\";src:url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:700;font-stretch:normal}.tk-birra-2{font-family:\"birra-2\",serif}"
},
{
"url": "https://use.typekit.net/ucs7mcf.css",
"content": "@import url(\"https://p.typekit.net/p.css?s=1&k=ucs7mcf&ht=tk&f=43886&a=23152309&app=typekit&e=css\");@font-face{font-family:\"flegrei\";src:url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400;font-stretch:normal}.tk-flegrei{font-family:\"flegrei\",sans-serif}"
},
{
"url": "https://use.typekit.net/erd0sed.css",
"content": "@import url(\"https://p.typekit.net/p.css?s=1&k=erd0sed&ht=tk&f=43885&a=23152309&app=typekit&e=css\");@font-face{font-family:\"pantelleria\";src:url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400;font-stretch:normal}.tk-pantelleria{font-family:\"pantelleria\",sans-serif}"
}
]
module.exports = {
cleanDistDir: false,
experimental: {
amp: {
validator: require.resolve('../../../../lib/amp-validator-wasm.js'),
},
},
}
import * as React from 'react'
import Document, { Main, NextScript, Head, Html } from 'next/document'
export default class MyDocument extends Document {
constructor(props) {
super(props)
const { __NEXT_DATA__, ids } = props
if (ids) {
__NEXT_DATA__.ids = ids
}
}
render() {
return (
<Html>
<Head>
<link rel="stylesheet" href="https://use.typekit.net/plm1izr.css" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import React from 'react'
const Page = () => {
return <div>Hi!</div>
}
export const config = { amp: true }
export default Page
import React from 'react'
import Link from 'next/link'
const Page = () => {
return (
<div>
Hi!
<br />
<br />
<Link href="/with-font" id="with-font">
With font
</Link>
</div>
)
}
export default Page
import React from 'react'
import Head from 'next/head'
const Page = () => {
return (
<>
<Head>
<link
href="https://use.typekit.net/erd0sed.css"
rel="stylesheet"
nonce="VmVyY2Vs"
/>
</Head>
<div>Hi!</div>
</>
)
}
export default Page
import Head from 'next/head'
function Home({ stars }) {
return (
<div className="container">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
<link
rel="stylesheet"
href="https://use.typekit.net/ucs7mcf.css"
></link>
</Head>
<main>
<div>Next stars: {stars}</div>
</main>
</div>
)
}
Home.getInitialProps = async () => {
return { stars: Math.random() * 1000 }
}
export default Home
import React from 'react'
import Head from 'next/head'
const Page = () => {
return (
<>
<Head>
<link href="https://use.typekit.net/erd0sed.css" rel="stylesheet" />
</Head>
<div>Hi!</div>
</>
)
}
export default Page
import Head from 'next/head'
import Link from 'next/link'
const WithFont = () => {
return (
<>
<Head>
<link href="https://use.typekit.net/ucs7mcf.css" rel="stylesheet" />
</Head>
<div id="with-font-container">
Page with custom fonts
<br />
<br />
<Link href="/without-font">Without font</Link>
</div>
</>
)
}
export const getServerSideProps = async () => {
return {
props: {},
}
}
export default WithFont
import Head from 'next/head'
import Link from 'next/link'
const WithoutFont = () => {
return (
<>
<Head>
<meta name="robots" content="noindex, nofollow" />
</Head>
<div>
Page without custom fonts
<br />
<br />
<Link href="/with-font">With font</Link>
</div>
</>
)
}
export const getServerSideProps = async () => {
return {
props: {},
}
}
export default WithoutFont
This diff is collapsed.
...@@ -264,7 +264,7 @@ describe('config telemetry', () => { ...@@ -264,7 +264,7 @@ describe('config telemetry', () => {
expect(event1).toMatch(/"@next\/next\/.+?": "(off|warn|error)"/) expect(event1).toMatch(/"@next\/next\/.+?": "(off|warn|error)"/)
}) })
it('emits telemery for usage of optimizeFonts, image, script & dynamic', async () => { it('emits telemery for usage of image, script & dynamic', async () => {
const { stderr } = await nextBuild(appDir, [], { const { stderr } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 }, env: { NEXT_TELEMETRY_DEBUG: 1 },
...@@ -277,10 +277,6 @@ describe('config telemetry', () => { ...@@ -277,10 +277,6 @@ describe('config telemetry', () => {
expect(featureUsageEvents).toEqual( expect(featureUsageEvents).toEqual(
expect.arrayContaining([ expect.arrayContaining([
{
featureName: 'optimizeFonts',
invocationCount: 1,
},
{ {
featureName: 'next/image', featureName: 'next/image',
invocationCount: 2, invocationCount: 2,
......
...@@ -10873,43 +10873,6 @@ ...@@ -10873,43 +10873,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/font-optimization/test/index.test.js": {
"passed": [
"Font Optimization with-google Font optimization for SSR apps production mode should skip this optimization for AMP pages",
"Font Optimization with-google Font optimization for unreachable font definitions. production mode should fallback to normal stylesheet if the contents of the fonts are unreachable",
"Font Optimization with-google Font optimization for unreachable font definitions. production mode should not inline multiple fallback link tag",
"Font Optimization with-typekit Font optimization for SSR apps production mode should skip this optimization for AMP pages",
"Font Optimization with-typekit Font optimization for unreachable font definitions. production mode should fallback to normal stylesheet if the contents of the fonts are unreachable",
"Font Optimization with-typekit Font optimization for unreachable font definitions. production mode should not inline multiple fallback link tag"
],
"failed": [
"Font Optimization font override production mode should inline font-override values",
"Font Optimization font override with size adjust production mode should inline font-override values",
"Font Optimization invalid configuration production mode should show a proper error if assetPrefix starts with .",
"Font Optimization with-google Font optimization for SSR apps production mode should add preconnect tag",
"Font Optimization with-google Font optimization for SSR apps production mode should inline the google fonts for SSR pages",
"Font Optimization with-google Font optimization for SSR apps production mode should inline the google fonts for static pages",
"Font Optimization with-google Font optimization for SSR apps production mode should inline the google fonts for static pages with Next/Head",
"Font Optimization with-google Font optimization for SSR apps production mode should only inline included fonts per page",
"Font Optimization with-google Font optimization for SSR apps production mode should pass nonce to the inlined font definition",
"Font Optimization with-google Font optimization for SSR apps production mode should work for fonts loaded on navigation",
"Font Optimization with-typekit Font optimization for SSR apps production mode should add preconnect tag",
"Font Optimization with-typekit Font optimization for SSR apps production mode should inline the typekit fonts for SSR pages",
"Font Optimization with-typekit Font optimization for SSR apps production mode should inline the typekit fonts for static pages",
"Font Optimization with-typekit Font optimization for SSR apps production mode should inline the typekit fonts for static pages with Next/Head",
"Font Optimization with-typekit Font optimization for SSR apps production mode should only inline included fonts per page",
"Font Optimization with-typekit Font optimization for SSR apps production mode should pass nonce to the inlined font definition",
"Font Optimization with-typekit Font optimization for SSR apps production mode should work for fonts loaded on navigation"
],
"pending": [
"Font Optimization Spread operator regression on <link>",
"Font Optimization makeStylesheetInert regression",
"Font Optimization with-google Font optimization for SSR apps production mode should work when build is cached",
"Font Optimization with-typekit Font optimization for SSR apps production mode should work when build is cached"
],
"flakey": [],
"runtimeError": false
},
"test/integration/future/test/index.test.js": { "test/integration/future/test/index.test.js": {
"passed": [ "passed": [
"excludeDefaultMomentLocales production mode should load momentjs" "excludeDefaultMomentLocales production mode should load momentjs"
...@@ -14956,7 +14919,7 @@ ...@@ -14956,7 +14919,7 @@
"config telemetry production mode emits telemetry for usage of swc plugins" "config telemetry production mode emits telemetry for usage of swc plugins"
], ],
"failed": [ "failed": [
"config telemetry production mode emits telemery for usage of optimizeFonts, image, script & dynamic", "config telemetry production mode emits telemery for usage of image, script & dynamic",
"config telemetry production mode emits telemetry for middleware related options", "config telemetry production mode emits telemetry for middleware related options",
"config telemetry production mode emits telemetry for transpilePackages", "config telemetry production mode emits telemetry for transpilePackages",
"config telemetry production mode emits telemetry for usage of @vercel/og", "config telemetry production mode emits telemetry for usage of @vercel/og",
...@@ -13033,41 +13033,6 @@ ...@@ -13033,41 +13033,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/font-optimization/test/index.test.js": {
"passed": [],
"failed": [],
"pending": [
"Font Optimization Spread operator regression on <link>",
"Font Optimization font override production mode should inline font-override values",
"Font Optimization font override with size adjust production mode should inline font-override values",
"Font Optimization invalid configuration production mode should show a proper error if assetPrefix starts with .",
"Font Optimization makeStylesheetInert regression",
"Font Optimization with-google Font optimization for SSR apps production mode should add preconnect tag",
"Font Optimization with-google Font optimization for SSR apps production mode should inline the google fonts for SSR pages",
"Font Optimization with-google Font optimization for SSR apps production mode should inline the google fonts for static pages",
"Font Optimization with-google Font optimization for SSR apps production mode should inline the google fonts for static pages with Next/Head",
"Font Optimization with-google Font optimization for SSR apps production mode should only inline included fonts per page",
"Font Optimization with-google Font optimization for SSR apps production mode should pass nonce to the inlined font definition",
"Font Optimization with-google Font optimization for SSR apps production mode should skip this optimization for AMP pages",
"Font Optimization with-google Font optimization for SSR apps production mode should work for fonts loaded on navigation",
"Font Optimization with-google Font optimization for SSR apps production mode should work when build is cached",
"Font Optimization with-google Font optimization for unreachable font definitions. production mode should fallback to normal stylesheet if the contents of the fonts are unreachable",
"Font Optimization with-google Font optimization for unreachable font definitions. production mode should not inline multiple fallback link tag",
"Font Optimization with-typekit Font optimization for SSR apps production mode should add preconnect tag",
"Font Optimization with-typekit Font optimization for SSR apps production mode should inline the typekit fonts for SSR pages",
"Font Optimization with-typekit Font optimization for SSR apps production mode should inline the typekit fonts for static pages",
"Font Optimization with-typekit Font optimization for SSR apps production mode should inline the typekit fonts for static pages with Next/Head",
"Font Optimization with-typekit Font optimization for SSR apps production mode should only inline included fonts per page",
"Font Optimization with-typekit Font optimization for SSR apps production mode should pass nonce to the inlined font definition",
"Font Optimization with-typekit Font optimization for SSR apps production mode should skip this optimization for AMP pages",
"Font Optimization with-typekit Font optimization for SSR apps production mode should work for fonts loaded on navigation",
"Font Optimization with-typekit Font optimization for SSR apps production mode should work when build is cached",
"Font Optimization with-typekit Font optimization for unreachable font definitions. production mode should fallback to normal stylesheet if the contents of the fonts are unreachable",
"Font Optimization with-typekit Font optimization for unreachable font definitions. production mode should not inline multiple fallback link tag"
],
"flakey": [],
"runtimeError": false
},
"test/integration/future/test/index.test.js": { "test/integration/future/test/index.test.js": {
"passed": [], "passed": [],
"failed": [], "failed": [],
...@@ -17069,7 +17034,7 @@ ...@@ -17069,7 +17034,7 @@
"config telemetry production mode detects i18n and image configs for session start", "config telemetry production mode detects i18n and image configs for session start",
"config telemetry production mode detects output config for session start", "config telemetry production mode detects output config for session start",
"config telemetry production mode detects rewrites, headers, and redirects for next build", "config telemetry production mode detects rewrites, headers, and redirects for next build",
"config telemetry production mode emits telemery for usage of optimizeFonts, image, script & dynamic", "config telemetry production mode emits telemery for usage of image, script & dynamic",
"config telemetry production mode emits telemetry for `next lint`", "config telemetry production mode emits telemetry for `next lint`",
"config telemetry production mode emits telemetry for configured React Compiler options", "config telemetry production mode emits telemetry for configured React Compiler options",
"config telemetry production mode emits telemetry for default React Compiler options", "config telemetry production mode emits telemetry for default React Compiler options",
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