Unverified Commit 8fdcc528 authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Font optimization (#21676)

Enable font optimization by default
parent bf629f94
...@@ -453,7 +453,7 @@ export default async function build( ...@@ -453,7 +453,7 @@ export default async function build(
BUILD_MANIFEST, BUILD_MANIFEST,
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
config.experimental.optimizeFonts config.optimizeFonts
? path.join( ? path.join(
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY, isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
FONT_MANIFEST FONT_MANIFEST
......
...@@ -1055,7 +1055,7 @@ export default async function getBaseWebpackConfig( ...@@ -1055,7 +1055,7 @@ export default async function getBaseWebpackConfig(
config.experimental.reactMode config.experimental.reactMode
), ),
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify( 'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
config.experimental.optimizeFonts && !dev config.optimizeFonts && !dev
), ),
'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify( 'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify(
config.experimental.optimizeImages config.experimental.optimizeImages
...@@ -1168,7 +1168,7 @@ export default async function getBaseWebpackConfig( ...@@ -1168,7 +1168,7 @@ export default async function getBaseWebpackConfig(
distDir, distDir,
}), }),
new ProfilingPlugin(), new ProfilingPlugin(),
config.experimental.optimizeFonts && config.optimizeFonts &&
!dev && !dev &&
isServer && isServer &&
(function () { (function () {
...@@ -1252,7 +1252,7 @@ export default async function getBaseWebpackConfig( ...@@ -1252,7 +1252,7 @@ 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, optimizeFonts: config.optimizeFonts,
optimizeImages: config.experimental.optimizeImages, optimizeImages: config.experimental.optimizeImages,
optimizeCss: config.experimental.optimizeCss, optimizeCss: config.experimental.optimizeCss,
scrollRestoration: config.experimental.scrollRestoration, scrollRestoration: config.experimental.scrollRestoration,
......
...@@ -16,9 +16,8 @@ import { ...@@ -16,9 +16,8 @@ import {
OPTIMIZED_FONT_PROVIDERS, OPTIMIZED_FONT_PROVIDERS,
} from '../../../next-server/lib/constants' } from '../../../next-server/lib/constants'
async function minifyCss(css: string): Promise<string> { function minifyCss(css: string): Promise<string> {
return new Promise((resolve) => return postcss([
postcss([
minifier({ minifier({
excludeAll: true, excludeAll: true,
discardComments: true, discardComments: true,
...@@ -26,10 +25,7 @@ async function minifyCss(css: string): Promise<string> { ...@@ -26,10 +25,7 @@ async function minifyCss(css: string): Promise<string> {
}), }),
]) ])
.process(css, { from: undefined }) .process(css, { from: undefined })
.then((res) => { .then((res) => res.css)
resolve(res.css)
})
)
} }
export class FontStylesheetGatheringPlugin { export class FontStylesheetGatheringPlugin {
...@@ -173,12 +169,15 @@ export class FontStylesheetGatheringPlugin { ...@@ -173,12 +169,15 @@ export class FontStylesheetGatheringPlugin {
this.manifestContent = [] this.manifestContent = []
for (let promiseIndex in fontDefinitionPromises) { for (let promiseIndex in fontDefinitionPromises) {
const css = await fontDefinitionPromises[promiseIndex] const css = await fontDefinitionPromises[promiseIndex]
if (css) {
const content = await minifyCss(css) const content = await minifyCss(css)
this.manifestContent.push({ this.manifestContent.push({
url: this.gatheredStylesheets[promiseIndex], url: this.gatheredStylesheets[promiseIndex],
content, content,
}) })
} }
}
if (!isWebpack5) { if (!isWebpack5) {
compilation.assets[FONT_MANIFEST] = new sources.RawSource( compilation.assets[FONT_MANIFEST] = new sources.RawSource(
JSON.stringify(this.manifestContent, null, ' ') JSON.stringify(this.manifestContent, null, ' ')
......
...@@ -534,7 +534,7 @@ export default async function exportApp( ...@@ -534,7 +534,7 @@ export default async function exportApp(
subFolders, subFolders,
buildExport: options.buildExport, buildExport: options.buildExport,
serverless: isTargetLikeServerless(nextConfig.target), serverless: isTargetLikeServerless(nextConfig.target),
optimizeFonts: nextConfig.experimental.optimizeFonts, optimizeFonts: nextConfig.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages, optimizeImages: nextConfig.experimental.optimizeImages,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
parentSpanId: pageExportSpan.id, parentSpanId: pageExportSpan.id,
......
...@@ -93,6 +93,7 @@ export const defaultConfig: NextConfig = { ...@@ -93,6 +93,7 @@ export const defaultConfig: NextConfig = {
trailingSlash: false, trailingSlash: false,
i18n: null, i18n: null,
productionBrowserSourceMaps: false, productionBrowserSourceMaps: false,
optimizeFonts: true,
experimental: { experimental: {
cpus: Math.max( cpus: Math.max(
1, 1,
...@@ -105,7 +106,6 @@ export const defaultConfig: NextConfig = { ...@@ -105,7 +106,6 @@ export const defaultConfig: NextConfig = {
reactMode: 'legacy', reactMode: 'legacy',
workerThreads: false, workerThreads: false,
pageEnv: false, pageEnv: false,
optimizeFonts: false,
optimizeImages: false, optimizeImages: false,
optimizeCss: false, optimizeCss: false,
scrollRestoration: false, scrollRestoration: false,
......
import * as Log from '../../build/output/log'
const https = require('https') const https = require('https')
const CHROME_UA = const CHROME_UA =
...@@ -10,9 +11,10 @@ export type FontManifest = Array<{ ...@@ -10,9 +11,10 @@ export type FontManifest = Array<{
}> }>
function getFontForUA(url: string, UA: string): Promise<String> { function getFontForUA(url: string, UA: string): Promise<String> {
return new Promise((resolve) => { return new Promise((resolve, reject) => {
let rawData: any = '' let rawData: any = ''
https.get( https
.get(
url, url,
{ {
headers: { headers: {
...@@ -28,6 +30,9 @@ function getFontForUA(url: string, UA: string): Promise<String> { ...@@ -28,6 +30,9 @@ function getFontForUA(url: string, UA: string): Promise<String> {
}) })
} }
) )
.on('error', (e: Error) => {
reject(e)
})
}) })
} }
...@@ -39,8 +44,16 @@ export async function getFontDefinitionFromNetwork( ...@@ -39,8 +44,16 @@ export async function getFontDefinitionFromNetwork(
* The order of IE -> Chrome is important, other wise chrome starts loading woff1. * The order of IE -> Chrome is important, other wise chrome starts loading woff1.
* CSS cascading 🤷‍♂️. * CSS cascading 🤷‍♂️.
*/ */
try {
result += await getFontForUA(url, IE_UA) result += await getFontForUA(url, IE_UA)
result += await getFontForUA(url, CHROME_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 return result
} }
......
...@@ -205,9 +205,9 @@ export default class Server { ...@@ -205,9 +205,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, optimizeFonts: !!this.nextConfig.optimizeFonts && !dev,
fontManifest: fontManifest:
this.nextConfig.experimental.optimizeFonts && !dev this.nextConfig.optimizeFonts && !dev
? requireFontManifest(this.distDir, this._isLikeServerless) ? requireFontManifest(this.distDir, this._isLikeServerless)
: null, : null,
optimizeImages: !!this.nextConfig.experimental.optimizeImages, optimizeImages: !!this.nextConfig.experimental.optimizeImages,
...@@ -272,9 +272,9 @@ export default class Server { ...@@ -272,9 +272,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 targeting both serverless and SSR by calling
* `process.env.__NEXT_OPTIMIZE_IMAGES`. * `process.env.__NEXT_OPTIMIZE_IMAGES`.
* TODO(atcastle@): Remove this when experimental.optimizeImages are being clened up. * TODO(atcastle@): Remove this when experimental.optimizeImages are being cleaned up.
*/ */
if (this.renderOpts.optimizeFonts) { if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
......
...@@ -398,7 +398,7 @@ export class Head extends Component< ...@@ -398,7 +398,7 @@ export class Head extends Component<
}) })
head = cssPreloads.concat(otherHeadElements) head = cssPreloads.concat(otherHeadElements)
} }
let children = this.props.children let children = React.Children.toArray(this.props.children).filter(Boolean)
// show a warning if Head contains <title> (only in development) // show a warning if Head contains <title> (only in development)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
children = React.Children.map(children, (child: any) => { children = React.Children.map(children, (child: any) => {
......
...@@ -99,7 +99,7 @@ describe('Build Output', () => { ...@@ -99,7 +99,7 @@ describe('Build Output', () => {
expect(parseFloat(indexFirstLoad)).toBeCloseTo(65.3, 1) expect(parseFloat(indexFirstLoad)).toBeCloseTo(65.3, 1)
expect(indexFirstLoad.endsWith('kB')).toBe(true) expect(indexFirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0) expect(parseFloat(err404Size)).toBeCloseTo(3.7, 1)
expect(err404Size.endsWith('kB')).toBe(true) expect(err404Size.endsWith('kB')).toBe(true)
expect(parseFloat(err404FirstLoad)).toBeCloseTo(68.5, 0) expect(parseFloat(err404FirstLoad)).toBeCloseTo(68.5, 0)
......
...@@ -19,6 +19,7 @@ export default class MyDocument extends Document { ...@@ -19,6 +19,7 @@ export default class MyDocument extends Document {
rel="stylesheet" rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Voces" href="https://fonts.googleapis.com/css?family=Voces"
/> />
{false && <script data-href="test"></script>}
</Head> </Head>
<body> <body>
<Main /> <Main />
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
initNextServerScript, initNextServerScript,
} from 'next-test-utils' } from 'next-test-utils'
import fs from 'fs-extra' import fs from 'fs-extra'
import cheerio from 'cheerio'
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
...@@ -54,13 +55,21 @@ function runTests() { ...@@ -54,13 +55,21 @@ function runTests() {
it('should pass nonce to the inlined font definition', async () => { it('should pass nonce to the inlined font definition', async () => {
const html = await renderViaHTTP(appPort, '/nonce') const html = await renderViaHTTP(appPort, '/nonce')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true) expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain(
'<link rel="stylesheet" nonce="VmVyY2Vs" data-href="https://fonts.googleapis.com/css2?family=Modak"/>' const link = $(
'link[rel="stylesheet"][data-href="https://fonts.googleapis.com/css2?family=Modak"]'
) )
expect(html).toMatch( const nonce = link.attr('nonce')
/<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Modak" nonce="VmVyY2Vs">.*<\/style>/ const style = $(
'style[data-href="https://fonts.googleapis.com/css2?family=Modak"]'
) )
const styleNonce = style.attr('nonce')
expect(link).toBeDefined()
expect(nonce).toBe('VmVyY2Vs')
expect(styleNonce).toBe('VmVyY2Vs')
}) })
it('should inline the google fonts for static pages with Next/Head', async () => { it('should inline the google fonts for static pages with Next/Head', async () => {
...@@ -117,11 +126,7 @@ function runTests() { ...@@ -117,11 +126,7 @@ function runTests() {
describe('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'))
...@@ -140,7 +145,7 @@ describe('Font optimization for serverless apps', () => { ...@@ -140,7 +145,7 @@ 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)
...@@ -157,7 +162,7 @@ describe('Font optimization for emulated serverless apps', () => { ...@@ -157,7 +162,7 @@ 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)
......
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