Unverified Commit 928ad979 authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

App font loader tree shaking (#41384)

Fixes tree shaking for font loaders in server components.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 562b5a38
......@@ -1967,12 +1967,10 @@ export default async function getBaseWebpackConfig(
(isClient
? new FlightManifestPlugin({
dev,
fontLoaderTargets,
})
: new FlightClientEntryPlugin({
dev,
isEdgeServer,
fontLoaderTargets,
})),
!dev &&
isClient &&
......
import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
import { getModuleBuildInfo } from './get-module-build-info'
import { regexCSS } from './utils'
export type ClientComponentImports = string[]
export type CssImports = Record<string, string[]>
......@@ -22,7 +23,7 @@ export default async function transformSource(this: any): Promise<string> {
const requests = modules as string[]
const code = requests
// Filter out css files on the server
.filter((request) => (isServer ? !request.endsWith('.css') : true))
.filter((request) => (isServer ? !regexCSS.test(request) : true))
.map((request) =>
request.endsWith('.css')
? `(() => import(/* webpackMode: "lazy" */ ${JSON.stringify(request)}))`
......
......@@ -10,3 +10,6 @@ export function isClientComponentModule(mod: {
const hasClientDirective = mod.buildInfo.rsc?.type === RSC_MODULE_TYPES.client
return hasClientDirective || imageRegex.test(mod.resource)
}
// TODO-APP: ensure .scss / .sass also works.
export const regexCSS = /\.css(\?.*)?$/
......@@ -19,12 +19,11 @@ import {
} from '../../../shared/lib/constants'
import { FlightCSSManifest, traverseModules } from './flight-manifest-plugin'
import { ASYNC_CLIENT_MODULES } from './flight-manifest-plugin'
import { isClientComponentModule } from '../loaders/utils'
import { isClientComponentModule, regexCSS } from '../loaders/utils'
interface Options {
dev: boolean
isEdgeServer: boolean
fontLoaderTargets?: string[]
}
const PLUGIN_NAME = 'ClientEntryPlugin'
......@@ -34,21 +33,16 @@ export const injectedClientEntries = new Map()
export const serverModuleIds = new Map<string, string | number>()
export const edgeServerModuleIds = new Map<string, string | number>()
// TODO-APP: ensure .scss / .sass also works.
const regexCSS = /\.css$/
// TODO-APP: move CSS manifest generation to the flight manifest plugin.
const flightCSSManifest: FlightCSSManifest = {}
export class FlightClientEntryPlugin {
dev: boolean
isEdgeServer: boolean
fontLoaderTargets?: string[]
constructor(options: Options) {
this.dev = options.dev
this.isEdgeServer = options.isEdgeServer
this.fontLoaderTargets = options.fontLoaderTargets
}
apply(compiler: webpack.Compiler) {
......@@ -376,18 +370,14 @@ export class FlightClientEntryPlugin {
// Request could be undefined or ''
if (!rawRequest) return
const isFontLoader = this.fontLoaderTargets?.some((fontLoaderTarget) =>
mod.userRequest.startsWith(`${fontLoaderTarget}?`)
)
const isCSS = regexCSS.test(rawRequest)
const modRequest: string | undefined =
!rawRequest.endsWith('.css') &&
!isCSS &&
!rawRequest.startsWith('.') &&
!rawRequest.startsWith('/') &&
!rawRequest.startsWith(APP_DIR_ALIAS)
? isFontLoader
? mod.userRequest
: rawRequest
: mod.resourceResolveData?.path
? rawRequest
: mod.resourceResolveData?.path + mod.resourceResolveData?.query
// Ensure module is not walked again if it's already been visited
if (!visitedBySegment[layoutOrPageRequest]) {
......@@ -401,7 +391,6 @@ export class FlightClientEntryPlugin {
}
visitedBySegment[layoutOrPageRequest].add(modRequest)
const isCSS = isFontLoader || regexCSS.test(modRequest)
const isClientComponent = isClientComponentModule(mod)
if (isCSS) {
......
......@@ -8,7 +8,7 @@
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { FLIGHT_MANIFEST } from '../../../shared/lib/constants'
import { relative } from 'path'
import { isClientComponentModule } from '../loaders/utils'
import { isClientComponentModule, regexCSS } from '../loaders/utils'
import {
edgeServerModuleIds,
......@@ -24,7 +24,6 @@ import {
interface Options {
dev: boolean
fontLoaderTargets?: string[]
}
/**
......@@ -111,11 +110,9 @@ export function traverseModules(
export class FlightManifestPlugin {
dev: Options['dev'] = false
fontLoaderTargets?: Options['fontLoaderTargets']
constructor(options: Options) {
this.dev = options.dev
this.fontLoaderTargets = options.fontLoaderTargets
}
apply(compiler: webpack.Compiler) {
......@@ -156,7 +153,6 @@ export class FlightManifestPlugin {
__edge_ssr_module_mapping__: {},
}
const dev = this.dev
const fontLoaderTargets = this.fontLoaderTargets
const clientRequestsSet = new Set()
......@@ -181,12 +177,8 @@ export class FlightManifestPlugin {
id: ModuleId,
mod: webpack.NormalModule
) {
const isFontLoader = fontLoaderTargets?.some((fontLoaderTarget) =>
mod.resource?.startsWith(`${fontLoaderTarget}?`)
)
const isCSSModule =
isFontLoader ||
mod.resource?.endsWith('.css') ||
regexCSS.test(mod.resource) ||
mod.type === 'css/mini-extract' ||
(!!mod.loaders &&
(dev
......
......@@ -582,9 +582,8 @@ function getPreloadedFontFilesInlineLinkTags(
const fontFiles = new Set<string>()
for (const css of layoutOrPageCss) {
// We only include the CSS if it's a global CSS, or it is used by this
// entrypoint.
if (serverCSSForEntries.includes(css) || !/\.module\.css/.test(css)) {
// We only include the CSS if it is used by this entrypoint.
if (serverCSSForEntries.includes(css)) {
const preloadedFontFiles = fontLoaderManifest.app[css]
if (preloadedFontFiles) {
for (const fontFile of preloadedFontFiles) {
......
......@@ -232,133 +232,135 @@ describe('app dir next-font', () => {
})
})
describe('preload', () => {
it('should preload correctly with server components', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(3)
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
if (!isDev) {
describe('preload', () => {
it('should preload correctly with server components', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(3)
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/b61859a50be14c53.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(2).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/b2104791981359ae.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/b2104791981359ae.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(2).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/b61859a50be14c53.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
it('should preload correctly with client components', async () => {
const html = await renderViaHTTP(next.url, '/client')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(3)
// From root layout
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
it('should preload correctly with client components', async () => {
const html = await renderViaHTTP(next.url, '/client')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(3)
// From root layout
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e1053f04babc7571.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(2).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/feab2c68f2a8e9a4.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e1053f04babc7571.p.woff2',
rel: 'preload',
type: 'font/woff2',
it('should preload correctly with layout using fonts', async () => {
const html = await renderViaHTTP(next.url, '/layout-with-fonts')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(2)
// From root layout
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/75c5faeeb9c86969.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
expect($('link[as="font"]').get(2).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/feab2c68f2a8e9a4.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
it('should preload correctly with layout using fonts', async () => {
const html = await renderViaHTTP(next.url, '/layout-with-fonts')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(2)
// From root layout
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/75c5faeeb9c86969.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
it('should preload correctly with page using fonts', async () => {
const html = await renderViaHTTP(next.url, '/page-with-fonts')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(2)
// From root layout
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/568e4c6d8123c4d6.p.woff2',
rel: 'preload',
type: 'font/woff2',
it('should preload correctly with page using fonts', async () => {
const html = await renderViaHTTP(next.url, '/page-with-fonts')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
expect($('link[as="font"]').length).toBe(2)
// From root layout
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: '',
href: '/_next/static/media/568e4c6d8123c4d6.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
})
})
}
if (isDev) {
describe('Dev errors', () => {
it('should recover on font loader error', async () => {
const browser = await webdriver(next.url, '/')
const font1Content = await next.readFile('fonts/font1.js')
const font1Content = await next.readFile('fonts/index.js')
// Break file
await next.patchFile(
'fonts/font1.js',
'fonts/index.js',
font1Content.replace('./font1.woff2', './does-not-exist.woff2')
)
expect(await hasRedbox(browser, true)).toBeTrue()
......@@ -367,7 +369,7 @@ describe('app dir next-font', () => {
)
// Fix file
await next.patchFile('fonts/font1.js', font1Content)
await next.patchFile('fonts/index.js', font1Content)
await browser.waitForElementByCss('#root-page')
})
})
......
import font3 from '../fonts/font3'
import { font3 } from '../fonts'
export default function Component() {
return (
......
'use client'
import font6 from '../../fonts/font6'
import { font6 } from '../../fonts'
export default function Component() {
return (
......
'use client'
import font4 from '../../fonts/font4'
import { font4 } from '../../fonts'
export default function Root({ children }) {
return (
......
'use client'
import Comp from './Comp'
import font5 from '../../fonts/font5'
import { font5 } from '../../fonts'
export default function HomePage() {
return (
......
import font1 from '../fonts/font1'
import { font1 } from '../fonts'
export default function Root({ children }) {
return (
......
import Comp from './Comp'
import font1 from '../fonts/font1'
import font2 from '../fonts/font2'
import { font1, font2 } from '../fonts'
export default function HomePage() {
return (
......
import localFont from '@next/font/local'
const font1 = localFont({ src: './font1.woff2', variable: '--font-1' })
export default font1
import localFont from '@next/font/local'
export const font2 = localFont({ src: './font2.woff2', variable: '--font-2' })
export default font2
import localFont from '@next/font/local'
export const font3 = localFont({
src: './font3.woff2',
weight: '900',
style: 'italic',
})
export default font3
import localFont from '@next/font/local'
export const font4 = localFont({ src: './font4.woff2', weight: '100' })
export default font4
import localFont from '@next/font/local'
export const font5 = localFont({
src: './font5.woff2',
style: 'italic',
preload: false,
})
export default font5
import localFont from '@next/font/local'
export const font6 = localFont({ src: './font6.woff2' })
export default font6
import localFont from '@next/font/local'
export const font1 = localFont({ src: './font1.woff2', variable: '--font-1' })
export const font2 = localFont({ src: './font2.woff2', variable: '--font-2' })
export const font3 = localFont({
src: './font3.woff2',
weight: '900',
style: 'italic',
})
export const font4 = localFont({ src: './font4.woff2', weight: '100' })
export const font5 = localFont({
src: './font5.woff2',
style: 'italic',
preload: false,
})
export const font6 = localFont({ src: './font6.woff2' })
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