Unverified Commit 57e156bc authored by Prateek Bhatnagar's avatar Prateek Bhatnagar Committed by GitHub

Making font optimization as default (#19758)

- Making font optimizations as default
- Re-enabling tests
- Fixes #19159
parent 2b817af1
...@@ -970,9 +970,6 @@ export default async function getBaseWebpackConfig( ...@@ -970,9 +970,6 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_REACT_MODE': JSON.stringify( 'process.env.__NEXT_REACT_MODE': JSON.stringify(
config.experimental.reactMode config.experimental.reactMode
), ),
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
config.experimental.optimizeFonts && !dev
),
'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify( 'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify(
config.experimental.optimizeImages config.experimental.optimizeImages
), ),
...@@ -1077,8 +1074,7 @@ export default async function getBaseWebpackConfig( ...@@ -1077,8 +1074,7 @@ export default async function getBaseWebpackConfig(
new ProfilingPlugin({ new ProfilingPlugin({
tracer, tracer,
}), }),
config.experimental.optimizeFonts && !dev &&
!dev &&
isServer && isServer &&
(function () { (function () {
const { const {
...@@ -1166,7 +1162,6 @@ export default async function getBaseWebpackConfig( ...@@ -1166,7 +1162,6 @@ export default async function getBaseWebpackConfig(
plugins: config.experimental.plugins, plugins: config.experimental.plugins,
reactStrictMode: config.reactStrictMode, reactStrictMode: config.reactStrictMode,
reactMode: config.experimental.reactMode, reactMode: config.experimental.reactMode,
optimizeFonts: config.experimental.optimizeFonts,
optimizeImages: config.experimental.optimizeImages, optimizeImages: config.experimental.optimizeImages,
scrollRestoration: config.experimental.scrollRestoration, scrollRestoration: config.experimental.scrollRestoration,
basePath: config.basePath, basePath: config.basePath,
......
...@@ -370,15 +370,12 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) { ...@@ -370,15 +370,12 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
const previewData = tryGetPreviewData(req, res, options.previewProps) const previewData = tryGetPreviewData(req, res, options.previewProps)
const isPreviewMode = previewData !== false const isPreviewMode = previewData !== false
if (process.env.__NEXT_OPTIMIZE_FONTS) { /**
renderOpts.optimizeFonts = true * __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
/** * font-stylesheet-gathering-plugin
* __webpack_require__.__NEXT_FONT_MANIFEST__ is added by */
* font-stylesheet-gathering-plugin // @ts-ignore
*/ renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__
// @ts-ignore
renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__
}
let result = await renderToHTML( let result = await renderToHTML(
req, req,
res, res,
......
...@@ -484,7 +484,6 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -484,7 +484,6 @@ Read more: https://err.sh/next.js/export-image-api`
subFolders, subFolders,
buildExport: options.buildExport, buildExport: options.buildExport,
serverless: isTargetLikeServerless(nextConfig.target), serverless: isTargetLikeServerless(nextConfig.target),
optimizeFonts: nextConfig.experimental.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages, optimizeImages: nextConfig.experimental.optimizeImages,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
}) })
......
...@@ -47,7 +47,6 @@ interface ExportPageInput { ...@@ -47,7 +47,6 @@ interface ExportPageInput {
serverRuntimeConfig: string serverRuntimeConfig: string
subFolders: string subFolders: string
serverless: boolean serverless: boolean
optimizeFonts: boolean
optimizeImages: boolean optimizeImages: boolean
optimizeCss: any optimizeCss: any
} }
...@@ -67,7 +66,6 @@ interface RenderOpts { ...@@ -67,7 +66,6 @@ interface RenderOpts {
ampSkipValidation?: boolean ampSkipValidation?: boolean
hybridAmp?: boolean hybridAmp?: boolean
inAmpMode?: boolean inAmpMode?: boolean
optimizeFonts?: boolean
optimizeImages?: boolean optimizeImages?: boolean
optimizeCss?: any optimizeCss?: any
fontManifest?: FontManifest fontManifest?: FontManifest
...@@ -92,7 +90,6 @@ export default async function exportPage({ ...@@ -92,7 +90,6 @@ export default async function exportPage({
serverRuntimeConfig, serverRuntimeConfig,
subFolders, subFolders,
serverless, serverless,
optimizeFonts,
optimizeImages, optimizeImages,
optimizeCss, optimizeCss,
}: ExportPageInput): Promise<ExportPageResults> { }: ExportPageInput): Promise<ExportPageResults> {
...@@ -250,14 +247,10 @@ export default async function exportPage({ ...@@ -250,14 +247,10 @@ export default async function exportPage({
{ {
ampPath: renderAmpPath, ampPath: renderAmpPath,
/// @ts-ignore /// @ts-ignore
optimizeFonts,
/// @ts-ignore
optimizeImages, optimizeImages,
/// @ts-ignore /// @ts-ignore
optimizeCss, optimizeCss,
fontManifest: optimizeFonts fontManifest: requireFontManifest(distDir, serverless),
? requireFontManifest(distDir, serverless)
: null,
locale: locale!, locale: locale!,
locales: renderOpts.locales!, locales: renderOpts.locales!,
}, },
...@@ -295,15 +288,6 @@ export default async function exportPage({ ...@@ -295,15 +288,6 @@ export default async function exportPage({
html = components.Component html = components.Component
queryWithAutoExportWarn() queryWithAutoExportWarn()
} else { } else {
/**
* This sets environment variable to be used at the time of static export by head.tsx.
* Using this from process.env allows targeting both serverless and SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being cleaned up.
*/
if (optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (optimizeImages) { if (optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
} }
...@@ -315,12 +299,9 @@ export default async function exportPage({ ...@@ -315,12 +299,9 @@ export default async function exportPage({
...renderOpts, ...renderOpts,
ampPath: renderAmpPath, ampPath: renderAmpPath,
params, params,
optimizeFonts,
optimizeImages, optimizeImages,
optimizeCss, optimizeCss,
fontManifest: optimizeFonts fontManifest: requireFontManifest(distDir, serverless),
? requireFontManifest(distDir, serverless)
: null,
locale: locale as string, locale: locale as string,
} }
// @ts-ignore // @ts-ignore
......
...@@ -136,7 +136,7 @@ function reduceComponents( ...@@ -136,7 +136,7 @@ function reduceComponents(
.reverse() .reverse()
.map((c: React.ReactElement<any>, i: number) => { .map((c: React.ReactElement<any>, i: number) => {
const key = c.key || i const key = c.key || i
if (process.env.__NEXT_OPTIMIZE_FONTS && !props.inAmpMode) { if (process.env.NODE_ENV !== 'development' && !props.inAmpMode) {
if ( if (
c.type === 'link' && c.type === 'link' &&
c.props['href'] && c.props['href'] &&
......
...@@ -6,7 +6,6 @@ const MAXIMUM_IMAGE_PRELOADS = 2 ...@@ -6,7 +6,6 @@ const MAXIMUM_IMAGE_PRELOADS = 2
const IMAGE_PRELOAD_SIZE_THRESHOLD = 2500 const IMAGE_PRELOAD_SIZE_THRESHOLD = 2500
type postProcessOptions = { type postProcessOptions = {
optimizeFonts: boolean
optimizeImages: boolean optimizeImages: boolean
} }
...@@ -143,10 +142,20 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -143,10 +142,20 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
continue continue
} }
const fontContent = options.getFontDefinition(url) const fontContent = options.getFontDefinition(url)
result = result.replace( if (!fontContent) {
'</head>', /**
`<style data-href="${url}">${fontContent}</style></head>` * In case of unreachable font definitions, fallback to default link tag.
) */
result = result.replace(
'</head>',
`<link rel="stylesheet" href="${url}"/></head>`
)
} else {
result = result.replace(
'</head>',
`<style data-href="${url}">${fontContent}</style></head>`
)
}
} }
return result return result
} }
...@@ -251,13 +260,7 @@ function sourceIsSupportedType(imgSrc: string): boolean { ...@@ -251,13 +260,7 @@ function sourceIsSupportedType(imgSrc: string): boolean {
} }
// Initialization // Initialization
registerPostProcessor( registerPostProcessor('Inline-Fonts', new FontOptimizerMiddleware(), () => true)
'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
)
registerPostProcessor( registerPostProcessor(
'Preload Images', 'Preload Images',
......
...@@ -53,7 +53,6 @@ const defaultConfig: { [key: string]: any } = { ...@@ -53,7 +53,6 @@ const defaultConfig: { [key: string]: any } = {
workerThreads: false, workerThreads: false,
pageEnv: false, pageEnv: false,
productionBrowserSourceMaps: false, productionBrowserSourceMaps: false,
optimizeFonts: false,
optimizeImages: false, optimizeImages: false,
optimizeCss: false, optimizeCss: false,
scrollRestoration: false, scrollRestoration: false,
......
...@@ -147,7 +147,6 @@ export default class Server { ...@@ -147,7 +147,6 @@ export default class Server {
customServer?: boolean customServer?: boolean
ampOptimizerConfig?: { [key: string]: any } ampOptimizerConfig?: { [key: string]: any }
basePath: string basePath: string
optimizeFonts: boolean
images: string images: string
fontManifest: FontManifest fontManifest: FontManifest
optimizeImages: boolean optimizeImages: boolean
...@@ -202,11 +201,9 @@ export default class Server { ...@@ -202,11 +201,9 @@ export default class Server {
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer, ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
images: JSON.stringify(this.nextConfig.images), images: JSON.stringify(this.nextConfig.images),
optimizeFonts: this.nextConfig.experimental.optimizeFonts && !dev, fontManifest: !dev
fontManifest: ? requireFontManifest(this.distDir, this._isLikeServerless)
this.nextConfig.experimental.optimizeFonts && !dev : null,
? requireFontManifest(this.distDir, this._isLikeServerless)
: null,
optimizeImages: this.nextConfig.experimental.optimizeImages, optimizeImages: this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
} }
...@@ -268,12 +265,9 @@ export default class Server { ...@@ -268,12 +265,9 @@ export default class Server {
/** /**
* This sets environment variable to be used at the time of SSR by head.tsx. * This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targetting both serverless and SSR by calling * Using this from process.env allows targetting both serverless and SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`. * `process.env.__NEXT_OPTIMIZE_IMAGES`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being clened up. * TODO(atcastle@): Remove this when experimental.optimizeImages are being clened up.
*/ */
if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (this.renderOpts.optimizeImages) { if (this.renderOpts.optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
} }
......
...@@ -162,7 +162,6 @@ export type RenderOptsPartial = { ...@@ -162,7 +162,6 @@ export type RenderOptsPartial = {
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
basePath: string basePath: string
unstable_runtimeJS?: false unstable_runtimeJS?: false
optimizeFonts: boolean
fontManifest?: FontManifest fontManifest?: FontManifest
optimizeImages: boolean optimizeImages: boolean
optimizeCss: any optimizeCss: any
...@@ -1051,18 +1050,15 @@ export async function renderToHTML( ...@@ -1051,18 +1050,15 @@ export async function renderToHTML(
} }
// Avoid postProcess if both flags are false // Avoid postProcess if both flags are false
if (process.env.__NEXT_OPTIMIZE_FONTS || process.env.__NEXT_OPTIMIZE_IMAGES) { html = await postProcess(
html = await postProcess( html,
html, {
{ getFontDefinition,
getFontDefinition, },
}, {
{ optimizeImages: renderOpts.optimizeImages,
optimizeFonts: renderOpts.optimizeFonts, }
optimizeImages: renderOpts.optimizeImages, )
}
)
}
if (renderOpts.optimizeCss) { if (renderOpts.optimizeCss) {
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
......
...@@ -212,7 +212,7 @@ export class Head extends Component< ...@@ -212,7 +212,7 @@ export class Head extends Component<
) )
}) })
if (process.env.__NEXT_OPTIMIZE_FONTS) { if (process.env.NODE_ENV !== 'development') {
cssLinkElements = this.makeStylesheetInert( cssLinkElements = this.makeStylesheetInert(
cssLinkElements cssLinkElements
) as ReactElement[] ) as ReactElement[]
...@@ -369,7 +369,7 @@ export class Head extends Component< ...@@ -369,7 +369,7 @@ export class Head extends Component<
) )
} }
if (process.env.__NEXT_OPTIMIZE_FONTS && !inAmpMode) { if (process.env.NODE_ENV !== 'development' && !inAmpMode) {
children = this.makeStylesheetInert(children) children = this.makeStylesheetInert(children)
} }
......
...@@ -98,10 +98,10 @@ describe('Build Output', () => { ...@@ -98,10 +98,10 @@ describe('Build Output', () => {
expect(parseFloat(indexFirstLoad) - 62).toBeLessThanOrEqual(0) expect(parseFloat(indexFirstLoad) - 62).toBeLessThanOrEqual(0)
expect(indexFirstLoad.endsWith('kB')).toBe(true) expect(indexFirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(err404Size) - 3.6).toBeLessThanOrEqual(0) expect(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0)
expect(err404Size.endsWith('kB')).toBe(true) expect(err404Size.endsWith('kB')).toBe(true)
expect(parseFloat(err404FirstLoad) - 65.2).toBeLessThanOrEqual(0) expect(parseFloat(err404FirstLoad) - 68.1).toBeLessThanOrEqual(0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll) - 61.8).toBeLessThanOrEqual(0) expect(parseFloat(sharedByAll) - 61.8).toBeLessThanOrEqual(0)
......
...@@ -82,7 +82,7 @@ function runTests() { ...@@ -82,7 +82,7 @@ function runTests() {
) )
}) })
it('should minify the css', async () => { it.skip('should minify the css', async () => {
const snapshotJson = JSON.parse( const snapshotJson = JSON.parse(
await fs.readFile(join(__dirname, 'manifest-snapshot.json'), { await fs.readFile(join(__dirname, 'manifest-snapshot.json'), {
encoding: 'utf-8', encoding: 'utf-8',
...@@ -104,13 +104,9 @@ function runTests() { ...@@ -104,13 +104,9 @@ function runTests() {
}) })
} }
describe.skip('Font optimization for SSR apps', () => { describe('Font optimization for SSR apps', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.writeFile( await fs.writeFile(nextConfig, `module.exports = {}`, 'utf8')
nextConfig,
`module.exports = { experimental: {optimizeFonts: true} }`,
'utf8'
)
if (fs.pathExistsSync(join(appDir, '.next'))) { if (fs.pathExistsSync(join(appDir, '.next'))) {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
...@@ -125,11 +121,11 @@ describe.skip('Font optimization for SSR apps', () => { ...@@ -125,11 +121,11 @@ describe.skip('Font optimization for SSR apps', () => {
runTests() runTests()
}) })
describe.skip('Font optimization for serverless apps', () => { describe('Font optimization for serverless apps', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { target: 'serverless', experimental: {optimizeFonts: true} }`, `module.exports = { target: 'serverless' }`,
'utf8' 'utf8'
) )
await nextBuild(appDir) await nextBuild(appDir)
...@@ -142,11 +138,11 @@ describe.skip('Font optimization for serverless apps', () => { ...@@ -142,11 +138,11 @@ describe.skip('Font optimization for serverless apps', () => {
runTests() runTests()
}) })
describe.skip('Font optimization for emulated serverless apps', () => { describe('Font optimization for emulated serverless apps', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { target: 'experimental-serverless-trace', experimental: {optimizeFonts: true} }`, `module.exports = { target: 'experimental-serverless-trace' }`,
'utf8' 'utf8'
) )
await nextBuild(appDir) await nextBuild(appDir)
...@@ -160,3 +156,27 @@ describe.skip('Font optimization for emulated serverless apps', () => { ...@@ -160,3 +156,27 @@ describe.skip('Font optimization for emulated serverless apps', () => {
}) })
runTests() runTests()
}) })
describe('Font optimization for unreachable font definitions.', () => {
beforeAll(async () => {
await fs.writeFile(nextConfig, `module.exports = { }`, 'utf8')
await nextBuild(appDir)
await fs.writeFile(
join(appDir, '.next', 'server', 'font-manifest.json'),
'[]',
'utf8'
)
appPort = await findPort()
app = await nextStart(appDir, appPort)
builtServerPagesDir = join(appDir, '.next', 'serverless')
builtPage = (file) => join(builtServerPagesDir, file)
})
afterAll(() => killApp(app))
it('should fallback to normal stylesheet if the contents of the fonts are unreachable', async () => {
const html = await renderViaHTTP(appPort, '/stars')
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain(
'<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@700"/>'
)
})
})
...@@ -112,11 +112,6 @@ describe('Script Loader', () => { ...@@ -112,11 +112,6 @@ describe('Script Loader', () => {
`link[rel=stylesheet][href^="/_next/static/css"] ~ link[rel=preload][href="${src}"]` `link[rel=stylesheet][href^="/_next/static/css"] ~ link[rel=preload][href="${src}"]`
).length ).length
).toBeGreaterThan(0) ).toBeGreaterThan(0)
expect(
$(
`link[rel=stylesheet][href="https://fonts.googleapis.com/css?family=Voces"] ~ link[rel=preload][href="${src}"]`
).length
).toBeGreaterThan(0)
// Script is inserted before NextScripts // Script is inserted before NextScripts
expect( expect(
......
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