Unverified Commit 75bbf00a authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Add local font loader (#40801)

Moves font related types to `next/font` so they can be reused in font
loaders.

Adds an argument to font loaders, the relative path from the app root to
the module consuming the loader. Needed for resolving local files
relative to the module calling it. Also used to improve error message.

Adds `@next/font/local` font loader. Similar to `@next/font/google` but
used to host locally downloaded font files.
parent 77c8a2c4
export { default } from '../dist/local/index'
throw new Error('@next/font/local is not correctly setup')
export { default } from '../dist/local/loader'
module.exports = require('../dist/local/loader')
......@@ -7,7 +7,8 @@
},
"files": [
"dist",
"google"
"google",
"local"
],
"license": "MIT",
"scripts": {
......
import type { FontModule } from 'next/font'
type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional'
type FontModule = {
className: string
variable: string
style: { fontFamily: string; fontWeight?: number; fontStyle?: string }
}
export declare function ABeeZee(options: {
variant: '400' | '400-italic'
display?: Display
......
import type { FontLoader } from 'next/font'
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
// @ts-ignore
......@@ -9,19 +10,12 @@ import {
validateData,
} from './utils'
type FontLoaderOptions = {
functionName: string
data: any[]
config: any
emitFontFile: (content: Buffer, ext: string, preload: boolean) => string
}
export default async function downloadGoogleFonts({
const downloadGoogleFonts: FontLoader = async ({
functionName,
data,
config,
emitFontFile,
}: FontLoaderOptions) {
}) => {
if (!config?.subsets) {
throw new Error(
'Please specify subsets for `@next/font/google` in your `next.config.js`'
......@@ -119,3 +113,5 @@ export default async function downloadGoogleFonts({
fallbackFonts: fallback,
}
}
export default downloadGoogleFonts
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { FontModule } from 'next/font'
type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional'
type LocalFont = {
src: string | Array<{ file: string; unicodeRange: string }>
display?: Display
weight?: string
style?: string
fallback?: string[]
preload?: boolean
ascentOverride?: string
descentOverride?: string
fontStretch?: string
fontVariant?: string
fontFeatureSettings?: string
fontVariationSettings?: string
lineGapOverride?: string
sizeAdjust?: string
}
export default function localFont(options: LocalFont): FontModule {
throw new Error()
}
import type { FontLoader } from 'next/font'
import { promisify } from 'util'
import { validateData } from './utils'
const fetchFonts: FontLoader = async ({
functionName,
data,
emitFontFile,
resolve,
fs,
}) => {
const {
family,
files,
display,
weight,
style,
fallback,
preload,
ascentOverride,
descentOverride,
lineGapOverride,
fontStretch,
fontFeatureSettings,
sizeAdjust,
} = validateData(functionName, data)
const fontFaces = await Promise.all(
files.map(async ({ file, ext, format, unicodeRange }) => {
const resolved = await resolve(file)
const fileBuffer = await promisify(fs.readFile)(resolved)
const fontUrl = emitFontFile(fileBuffer, ext, preload)
const fontFaceProperties = [
['font-family', `'${family}'`],
['src', `url(${fontUrl}) format('${format}')`],
['font-display', display],
...(weight ? [['font-weight', weight]] : []),
...(style ? [['font-style', style]] : []),
...(ascentOverride ? [['ascent-override', ascentOverride]] : []),
...(descentOverride ? [['descent-override', descentOverride]] : []),
...(lineGapOverride ? [['line-gap-override', lineGapOverride]] : []),
...(fontStretch ? [['font-stretch', fontStretch]] : []),
...(fontFeatureSettings
? [['font-feature-settings', fontFeatureSettings]]
: []),
...(sizeAdjust ? [['size-adjust', sizeAdjust]] : []),
...(unicodeRange ? [['unicode-range', unicodeRange]] : ''),
]
return `@font-face {
${fontFaceProperties
.map(([property, value]) => `${property}: ${value};`)
.join('\n')}
}`
})
)
return {
css: fontFaces.join('\n'),
fallbackFonts: fallback,
}
}
export default fetchFonts
const allowedDisplayValues = ['auto', 'block', 'swap', 'fallback', 'optional']
const formatValues = (values: string[]) =>
values.map((val) => `\`${val}\``).join(', ')
const extToFormat = {
woff: 'woff',
woff2: 'woff2',
ttf: 'truetype',
otf: 'opentype',
eot: 'embedded-opentype',
}
type FontOptions = {
family: string
files: Array<{
file: string
ext: string
format: string
unicodeRange?: string
}>
display: string
weight?: string
style?: string
fallback?: string[]
preload: boolean
ascentOverride?: string
descentOverride?: string
fontStretch?: string
fontVariant?: string
fontFeatureSettings?: string
fontVariationSettings?: string
lineGapOverride?: string
sizeAdjust?: string
}
export function validateData(functionName: string, data: any): FontOptions {
if (functionName) {
throw new Error(`@next/font/local has no named exports`)
}
let {
src,
display = 'optional',
weight,
style,
fallback,
preload = true,
ascentOverride,
descentOverride,
fontStretch,
fontVariant,
fontFeatureSettings,
fontVariationSettings,
lineGapOverride,
sizeAdjust,
} = data[0] || ({} as any)
if (!allowedDisplayValues.includes(display)) {
throw new Error(
`Invalid display value \`${display}\`.\nAvailable display values: ${formatValues(
allowedDisplayValues
)}`
)
}
const srcArray = Array.isArray(src) ? src : [{ file: src }]
if (srcArray.length === 0) {
throw new Error('Src must contain one or more files')
}
const files = srcArray.map(({ file, unicodeRange }) => {
if (!file) {
throw new Error('Src array objects must have a `file` property')
}
if (srcArray.length > 1 && !unicodeRange) {
throw new Error(
"Files must have a unicode-range if there's more than one"
)
}
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(file)?.[1]
if (!ext) {
throw new Error(`Unexpected file \`${file}\``)
}
return {
file,
unicodeRange,
ext,
format: extToFormat[ext as 'woff' | 'woff2' | 'eot' | 'ttf' | 'otf'],
}
})
const family = /.+\/(.+?)\./.exec(files[0].file)![1]
return {
family,
files,
display,
weight,
style,
fallback,
preload,
ascentOverride,
descentOverride,
fontStretch,
fontVariant,
fontFeatureSettings,
fontVariationSettings,
lineGapOverride,
sizeAdjust,
}
}
......@@ -36,7 +36,6 @@ use serde::Deserialize;
use std::cell::RefCell;
use std::rc::Rc;
use std::{path::PathBuf, sync::Arc};
use swc_core::ecma::atoms::JsWord;
use swc_core::{
base::config::ModuleConfig,
......@@ -113,7 +112,7 @@ pub struct TransformOptions {
pub modularize_imports: Option<modularize_imports::Config>,
#[serde(default)]
pub font_loaders: Option<Vec<JsWord>>,
pub font_loaders: Option<next_font_loaders::Config>,
}
pub fn custom_before_pass<'a, C: Comments + 'a>(
......@@ -218,10 +217,9 @@ where
None => Either::Right(noop()),
},
match &opts.font_loaders {
Some(font_loaders) =>
Either::Left(next_font_loaders::next_font_loaders(font_loaders.clone())),
Some(config) => Either::Left(next_font_loaders::next_font_loaders(config.clone())),
None => Either::Right(noop()),
}
},
)
}
......
......@@ -7,6 +7,7 @@ use swc_core::ecma::visit::{noop_visit_type, Visit};
pub struct FontImportsGenerator<'a> {
pub state: &'a mut super::State,
pub relative_path: &'a str,
}
impl<'a> FontImportsGenerator<'a> {
......@@ -41,7 +42,7 @@ impl<'a> FontImportsGenerator<'a> {
Some(function) => String::from(&**function),
None => String::new(),
};
let mut values = vec![function_name];
let mut values = vec![self.relative_path.to_string(), function_name];
values.append(&mut json_values);
return Some(ImportDecl {
......
use fxhash::FxHashSet;
use serde::Deserialize;
use swc_core::{
common::{collections::AHashMap, BytePos, Spanned},
ecma::{
......@@ -12,9 +13,16 @@ mod find_functions_outside_module_scope;
mod font_functions_collector;
mod font_imports_generator;
pub fn next_font_loaders(font_loaders: Vec<JsWord>) -> impl Fold + VisitMut {
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config {
pub font_loaders: Vec<JsWord>,
pub relative_file_path_from_root: JsWord,
}
pub fn next_font_loaders(config: Config) -> impl Fold + VisitMut {
as_folder(NextFontLoaders {
font_loaders,
config,
state: State {
..Default::default()
},
......@@ -35,7 +43,7 @@ pub struct State {
}
struct NextFontLoaders {
font_loaders: Vec<JsWord>,
config: Config,
state: State,
}
......@@ -45,7 +53,7 @@ impl VisitMut for NextFontLoaders {
fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) {
// Find imported functions from font loaders
let mut functions_collector = font_functions_collector::FontFunctionsCollector {
font_loaders: &self.font_loaders,
font_loaders: &self.config.font_loaders,
state: &mut self.state,
};
items.visit_with(&mut functions_collector);
......@@ -54,6 +62,7 @@ impl VisitMut for NextFontLoaders {
// Generate imports from font function calls
let mut import_generator = font_imports_generator::FontImportsGenerator {
state: &mut self.state,
relative_path: &self.config.relative_file_path_from_root,
};
items.visit_with(&mut import_generator);
......
use next_swc::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic,
next_font_loaders::next_font_loaders, next_ssg::next_ssg,
disallow_re_export_all_in_page::disallow_re_export_all_in_page,
next_dynamic::next_dynamic,
next_font_loaders::{next_font_loaders, Config as FontLoaderConfig},
next_ssg::next_ssg,
react_server_components::server_components,
};
use std::path::PathBuf;
......@@ -101,7 +103,12 @@ fn next_font_loaders_errors(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture_allowing_error(
syntax(),
&|_tr| next_font_loaders(vec!["@next/font/google".into(), "cool-fonts".into()]),
&|_tr| {
next_font_loaders(FontLoaderConfig {
relative_file_path_from_root: "pages/test.tsx".into(),
font_loaders: vec!["@next/font/google".into(), "cool-fonts".into()],
})
},
&input,
&output,
);
......
import inter1 from '@next/font/google?Inter;{"variant":"400"}';
import inter2 from '@next/font/google?Inter;{"variant":"400"}';
import inter1 from '@next/font/google?pages/test.tsx;Inter;{"variant":"400"}';
import inter2 from '@next/font/google?pages/test.tsx;Inter;{"variant":"400"}';
var i = 10;
var i2 = 20;
import a from "@next/font/google?ABeeZee;{}";
import a from "@next/font/google?ABeeZee;{}";
import a from "@next/font/google?ABeeZee;{}";
import a from "@next/font/google?ABeeZee;{}";
import a from "@next/font/google?pages/test.tsx;ABeeZee;{}";
import a from "@next/font/google?pages/test.tsx;ABeeZee;{}";
import a from "@next/font/google?pages/test.tsx;ABeeZee;{}";
import a from "@next/font/google?pages/test.tsx;ABeeZee;{}";
const a = fn({
10: 'hello'
});
......
import inter from "@next/font/google?Inter;{};[]";
import inter from "@next/font/google?pages/test.tsx;Inter;{};[]";
const a = fn(...{}, ...[]);
use next_swc::{
amp_attributes::amp_attributes,
next_dynamic::next_dynamic,
next_font_loaders::next_font_loaders,
next_font_loaders::{next_font_loaders, Config as FontLoaderConfig},
next_ssg::next_ssg,
page_config::page_config_test,
react_remove_properties::remove_properties,
......@@ -255,7 +255,12 @@ fn next_font_loaders_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| next_font_loaders(vec!["@next/font/google".into(), "cool-fonts".into()]),
&|_tr| {
next_font_loaders(FontLoaderConfig {
relative_file_path_from_root: "pages/test.tsx".into(),
font_loaders: vec!["@next/font/google".into(), "cool-fonts".into()],
})
},
&input,
&output,
);
......
import font from 'cool-fonts?;{"prop":true}';
import font from 'cool-fonts?pages/test.tsx;;{"prop":true}';
import firaCode from "@next/font/google?Abel";
import inter from "@next/font/google?Inter";
import firaCode from "@next/font/google?pages/test.tsx;Abel";
import inter from "@next/font/google?pages/test.tsx;Inter";
import React from 'react';
export { firaCode };
export default inter;
import firaCode from '@next/font/google?Fira_Code;{"fallback":["system-ui",{"key":false},[]],"key":{"key2":{}},"preload":true,"variant":"400"}';
import firaCode from '@next/font/google?pages/test.tsx;Fira_Code;{"fallback":["system-ui",{"key":false},[]],"key":{"key2":{}},"preload":true,"variant":"400"}';
import React from 'react';
console.log(firaCode);
import acme1 from 'cool-fonts?Acme;{"variant":"400"}';
import acme1 from 'cool-fonts?pages/test.tsx;Acme;{"variant":"400"}';
import React from 'react';
import geo from '@next/font/google?Geo;"test";[1.0];{"a":2.0};3.0';
import geo from '@next/font/google?pages/test.tsx;Geo;"test";[1.0];{"a":2.0};3.0';
import inter from '@next/font/google?Inter;{"display":"swap","variant":"900"}';
import inter from '@next/font/google?Inter;{"display":"swap","variant":"900"}';
import inter from '@next/font/google?pages/test.tsx;Inter;{"display":"swap","variant":"900"}';
import inter from '@next/font/google?pages/test.tsx;Inter;{"display":"swap","variant":"900"}';
import React from 'react';
import inter from '@next/font/google?Inter;{"variant":"900"}';
import fira from 'cool-fonts?Fira_Code;{"display":"swap","variant":"400"}';
import inter from '@next/font/google?pages/test.tsx;Inter;{"variant":"900"}';
import fira from 'cool-fonts?pages/test.tsx;Fira_Code;{"display":"swap","variant":"400"}';
import React from 'react';
import firaCode from '@next/font/google?Fira_Code;{"fallback":["system-ui"],"variant":"400"}';
import inter from '@next/font/google?Inter;{"display":"swap","variant":"900"}';
import firaCode from '@next/font/google?pages/test.tsx;Fira_Code;{"fallback":["system-ui"],"variant":"400"}';
import inter from '@next/font/google?pages/test.tsx;Inter;{"display":"swap","variant":"900"}';
import React from 'react';
import inter from '@next/font/google?Inter;{"variant":"900"}';
import fira from '@next/font/google?Fira_Code;{"display":"swap","variant":"400"}';
import inter from '@next/font/google?pages/test.tsx;Inter;{"variant":"900"}';
import fira from '@next/font/google?pages/test.tsx;Fira_Code;{"display":"swap","variant":"400"}';
import React from 'react';
import fira from "@next/font/google?Fira_Code";
import fira from "@next/font/google?pages/test.tsx;Fira_Code";
......@@ -33,6 +33,7 @@ function getBaseSWCOptions({
jsConfig,
swcCacheDir,
isServerLayer,
relativeFilePathFromRoot,
}) {
const parserConfig = getParserOptions({ filename, jsConfig })
const paths = jsConfig?.compilerOptions?.paths
......@@ -124,8 +125,12 @@ function getBaseSWCOptions({
}
: false,
fontLoaders:
nextConfig?.experimental?.fontLoaders &&
Object.keys(nextConfig.experimental.fontLoaders),
nextConfig?.experimental?.fontLoaders && relativeFilePathFromRoot
? {
fontLoaders: Object.keys(nextConfig.experimental.fontLoaders),
relativeFilePathFromRoot,
}
: null,
}
}
......@@ -220,6 +225,7 @@ export function getLoaderSWCOptions({
jsConfig,
supportedBrowsers,
swcCacheDir,
relativeFilePathFromRoot,
// This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl,
}) {
......@@ -233,6 +239,7 @@ export function getLoaderSWCOptions({
// resolvedBaseUrl,
swcCacheDir,
isServerLayer,
relativeFilePathFromRoot,
})
const isNextDist = nextDistPath.test(filename)
......
......@@ -646,6 +646,7 @@ export default async function getBaseWebpackConfig(
loader: 'next-swc-loader',
options: {
isServer: isNodeServer || isEdgeServer,
rootDir: dir,
pagesDir,
hasReactRefresh: dev && isClient,
fileReading: config.experimental.swcFileReading,
......
import type { FontLoader } from '../../../../font'
import path from 'path'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import postcssFontLoaderPlugn from './postcss-font-loader'
type FontLoader = (options: {
functionName: string
data: any[]
config: any
emitFontFile: (content: Buffer, ext: string, preload: boolean) => string
}) => Promise<{ css: string; fallbackFonts: string[] }>
import { promisify } from 'util'
import chalk from 'next/dist/compiled/chalk'
export default async function nextFontLoader(this: any) {
const fontLoaderSpan = this.currentTraceSpan.traceChild('next-font-loader')
......@@ -36,7 +33,9 @@ export default async function nextFontLoader(this: any) {
}
// next-swc next_font_loaders turns each function call argument into JSON seperated by semicolons
let [functionName, ...data] = this.resourceQuery.slice(1).split(';')
let [relativeFilePathFromRoot, functionName, ...data] = this.resourceQuery
.slice(1)
.split(';')
data = data.map((value: string) => JSON.parse(value))
try {
......@@ -49,6 +48,12 @@ export default async function nextFontLoader(this: any) {
data,
config: fontLoaderOptions,
emitFontFile,
resolve: (src: string) =>
promisify(this.resolve)(
path.dirname(path.join(this.rootContext, relativeFilePathFromRoot)),
src
),
fs: this.fs,
})
const { postcss } = await getPostcss()
......@@ -77,6 +82,9 @@ export default async function nextFontLoader(this: any) {
callback(null, result.css, null, { exports, ast, fontFamilyHash })
} catch (err: any) {
err.stack = false
err.message += `
${chalk.cyan(`Location: ${relativeFilePathFromRoot}`)}`
callback(err)
}
})
......
......@@ -28,7 +28,7 @@ DEALINGS IN THE SOFTWARE.
import { isWasm, transform } from '../../swc'
import { getLoaderSWCOptions } from '../../swc/options'
import { isAbsolute } from 'path'
import path, { isAbsolute } from 'path'
async function loaderTransform(parentTrace, source, inputSourceMap) {
// Make the loader async
......@@ -39,6 +39,7 @@ async function loaderTransform(parentTrace, source, inputSourceMap) {
const {
isServer,
isServerLayer,
rootDir,
pagesDir,
hasReactRefresh,
nextConfig,
......@@ -47,6 +48,7 @@ async function loaderTransform(parentTrace, source, inputSourceMap) {
swcCacheDir,
} = loaderOptions
const isPageFile = filename.startsWith(pagesDir)
const relativeFilePathFromRoot = path.relative(rootDir, filename)
const swcOptions = getLoaderSWCOptions({
pagesDir,
......@@ -60,6 +62,7 @@ async function loaderTransform(parentTrace, source, inputSourceMap) {
jsConfig,
supportedBrowsers,
swcCacheDir,
relativeFilePathFromRoot,
})
const programmaticOptions = {
......
export type FontModule = {
className: string
variable: string
style: { fontFamily: string; fontWeight?: number; fontStyle?: string }
}
export type FontLoader = (options: {
functionName: string
data: any[]
config: any
emitFontFile: (content: Buffer, ext: string, preload: boolean) => string
resolve: (src: string) => string
fs: any
}) => Promise<{ css: string; fallbackFonts?: string[] }>
......@@ -7,8 +7,8 @@ const fetch = require('node-fetch')
'https://fonts.google.com/metadata/fonts'
).then((r) => r.json())
let fontFunctions = `type Display = 'auto'|'block'|'swap'|'fallback'|'optional'
type FontModule = { className: string, variable: string, style: { fontFamily: string, fontWeight?: number, fontStyle?: string } }
let fontFunctions = `import type { FontModule } from 'next/font'
type Display = 'auto'|'block'|'swap'|'fallback'|'optional'
`
const fontData = {}
for (let { family, fonts, axes } of familyMetadataList) {
......
fake font
\ No newline at end of file
my other fake font
\ No newline at end of file
......@@ -4,6 +4,7 @@ module.exports = {
'@next/font/google': {
subsets: ['latin'],
},
'@next/font/local': {},
},
},
}
import localFont from '@next/font/local'
const myFont1 = localFont({
src: '../fonts/my-font.woff2',
style: 'italic',
weight: '100',
})
const myFont2 = localFont({
src: '../fonts/my-other-font.woff',
preload: false,
})
export default function WithFonts() {
return (
<>
<div id="first-local-font" className={myFont1.className}>
{JSON.stringify(myFont1)}
</div>
<div id="second-local-font" className={myFont2.className}>
{JSON.stringify(myFont2)}
</div>
</>
)
}
......@@ -22,6 +22,7 @@ describe('@next/font/google', () => {
files: {
pages: new FileRef(join(__dirname, 'app/pages')),
components: new FileRef(join(__dirname, 'app/components')),
fonts: new FileRef(join(__dirname, 'app/fonts')),
'next.config.js': new FileRef(join(__dirname, 'app/next.config.js')),
},
dependencies: {
......@@ -79,6 +80,39 @@ describe('@next/font/google', () => {
},
})
})
test('page with local fonts', async () => {
const html = await renderViaHTTP(next.url, '/with-local-fonts')
const $ = cheerio.load(html)
// _app.js
expect(JSON.parse($('#app-open-sans').text())).toEqual({
className: expect.any(String),
variable: expect.any(String),
style: {
fontFamily: "'__Open_Sans_bbc724', '__open-sans-fallback_bbc724'",
fontStyle: 'normal',
},
})
// with-local-fonts.js
expect(JSON.parse($('#first-local-font').text())).toEqual({
className: expect.any(String),
variable: expect.any(String),
style: {
fontFamily: "'__my-font_2cddd5'",
fontStyle: 'italic',
fontWeight: 100,
},
})
expect(JSON.parse($('#second-local-font').text())).toEqual({
className: expect.any(String),
variable: expect.any(String),
style: {
fontFamily: "'__my-other-font_0a2813'",
},
})
})
})
describe('computed styles', () => {
......@@ -290,5 +324,32 @@ describe('@next/font/google', () => {
type: 'font/woff2',
})
})
test('page with local fonts', async () => {
const html = await renderViaHTTP(next.url, '/with-local-fonts')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
// Preload
expect($('link[as="font"]').length).toBe(2)
// _app
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: 'anonymous',
href: '/_next/static/fonts/0812efcfaefec5ea.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
// with-local-fonts
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: 'anonymous',
href: '/_next/static/fonts/7be88d77534e80fd.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
})
})
})
......@@ -30,6 +30,9 @@ describe('@next/font/google with-font-declarations-file', () => {
'fonts.js': new FileRef(
join(__dirname, 'with-font-declarations-file/fonts.js')
),
'my-font.woff2': new FileRef(
join(__dirname, 'with-font-declarations-file/my-font.woff2')
),
'next.config.js': new FileRef(
join(__dirname, 'with-font-declarations-file/next.config.js')
),
......@@ -53,7 +56,7 @@ describe('@next/font/google with-font-declarations-file', () => {
if (isDev) {
// In dev all fonts will be preloaded since it's before DCE
expect($('link[as="font"]').length).toBe(3)
expect($('link[as="font"]').length).toBe(4)
} else {
// Preload
expect($('link[as="font"]').length).toBe(2)
......@@ -85,7 +88,7 @@ describe('@next/font/google with-font-declarations-file', () => {
if (isDev) {
// In dev all fonts will be preloaded since it's before DCE
expect($('link[as="font"]').length).toBe(3)
expect($('link[as="font"]').length).toBe(4)
} else {
// Preload
expect($('link[as="font"]').length).toBe(2)
......@@ -107,4 +110,36 @@ describe('@next/font/google with-font-declarations-file', () => {
})
}
})
test('preload correct files at /local-font', async () => {
const html = await renderViaHTTP(next.url, '/local-font')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
if (isDev) {
// In dev all fonts will be preloaded since it's before DCE
expect($('link[as="font"]').length).toBe(4)
} else {
// Preload
expect($('link[as="font"]').length).toBe(2)
// From /_app
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: 'anonymous',
href: '/_next/static/fonts/0812efcfaefec5ea.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
// From /local-font
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: 'anonymous',
href: '/_next/static/fonts/2a931eed088772c9.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
}
})
})
import localFont from '@next/font/local'
import {
Open_Sans,
Source_Code_Pro,
......@@ -13,4 +14,8 @@ const abel = Abel({ variant: '400', display: 'optional', preload: false })
const inter = Inter({ display: 'block', preload: true })
const roboto = Roboto({ variant: '400' })
export { openSans, sourceCodePro, abel, inter, roboto }
const myLocalFont = localFont({
src: './my-font.woff2',
})
export { openSans, sourceCodePro, abel, inter, roboto, myLocalFont }
fake font data
\ No newline at end of file
......@@ -4,6 +4,7 @@ module.exports = {
'@next/font/google': {
subsets: ['latin'],
},
'@next/font/local': {},
},
},
}
import { myLocalFont } from '../fonts'
export default function LocalFont() {
return <p className={myLocalFont.className}>Hello world!</p>
}
......@@ -78,6 +78,8 @@ describe('@next/font/google loader', () => {
data: [{ adjustFontFallback: false, ...data }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
expect(css).toBe('OK')
expect(fetch).toHaveBeenCalledTimes(1)
......@@ -96,6 +98,8 @@ describe('@next/font/google loader', () => {
data: [],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
expect(css).toMatchInlineSnapshot(`
"
......@@ -121,6 +125,8 @@ describe('@next/font/google loader', () => {
data: [],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
expect(css).toMatchInlineSnapshot(`
"
......@@ -146,6 +152,8 @@ describe('@next/font/google loader', () => {
data: [{ fallback: ['Abc', 'Def'] }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
expect(css).toMatchInlineSnapshot(`
"
......@@ -171,6 +179,8 @@ describe('@next/font/google loader', () => {
data: [{ adjustFontFallback: false, fallback: ['system-ui', 'Arial'] }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
expect(css).toBe('')
expect(fallbackFonts).toEqual(['system-ui', 'Arial'])
......@@ -189,6 +199,8 @@ describe('@next/font/google loader', () => {
data: [],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Failed to fetch font \`Inter\`.
......@@ -203,6 +215,8 @@ describe('@next/font/google loader', () => {
data: [],
config: undefined,
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Please specify subsets for \`@next/font/google\` in your \`next.config.js\`"`
......@@ -216,6 +230,8 @@ describe('@next/font/google loader', () => {
data: [],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"@next/font/google has no default export"`
......@@ -229,6 +245,8 @@ describe('@next/font/google loader', () => {
data: [],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unknown font \`Unknown Font\`"`
......@@ -242,6 +260,8 @@ describe('@next/font/google loader', () => {
data: [{ variant: '123' }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Unknown variant \`123\` for font \`Inter\`.
......@@ -256,6 +276,8 @@ describe('@next/font/google loader', () => {
data: [],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Missing variant for font \`Abel\`.
......@@ -270,6 +292,8 @@ describe('@next/font/google loader', () => {
data: [{ display: 'invalid' }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid display value \`invalid\` for font \`Inter\`.
......@@ -284,6 +308,8 @@ describe('@next/font/google loader', () => {
data: [{ variant: '400', axes: [] }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Axes can only be defined for variable fonts"`
......@@ -297,6 +323,8 @@ describe('@next/font/google loader', () => {
data: [{ axes: [] }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Font \`Lora\` has no definable \`axes\`"`
......@@ -310,6 +338,8 @@ describe('@next/font/google loader', () => {
data: [{ axes: true }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value for font \`Inter\`, expected an array of axes.
......@@ -324,6 +354,8 @@ describe('@next/font/google loader', () => {
data: [{ axes: ['INVALID'] }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value \`INVALID\` for font \`Roboto Flex\`.
......
import loader from '@next/font/local/loader'
describe('@next/font/local', () => {
describe('generated CSS', () => {
test('Default CSS', async () => {
const { css } = await loader({
functionName: '',
data: [{ src: './my-font.woff2' }],
config: {},
emitFontFile: () => '/_next/static/fonts/my-font.woff2',
resolve: jest.fn(),
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'my-font';
src: url(/_next/static/fonts/my-font.woff2) format('woff2');
font-display: optional;
}"
`)
})
test('Default CSS - src array with unicodeRange', async () => {
const { css } = await loader({
functionName: '',
data: [
{ src: [{ file: './my-font.woff2', unicodeRange: 'unicode-range' }] },
],
config: {},
emitFontFile: () => '/_next/static/fonts/my-font.woff2',
resolve: jest.fn(),
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'my-font';
src: url(/_next/static/fonts/my-font.woff2) format('woff2');
font-display: optional;
unicode-range: unicode-range;
}"
`)
})
test('Default CSS - src array without unicodeRange', async () => {
const { css } = await loader({
functionName: '',
data: [{ src: [{ file: './my-font.woff2' }] }],
config: {},
emitFontFile: () => '/_next/static/fonts/my-font.woff2',
resolve: jest.fn(),
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'my-font';
src: url(/_next/static/fonts/my-font.woff2) format('woff2');
font-display: optional;
}"
`)
})
test('Weight and style', async () => {
const { css } = await loader({
functionName: '',
data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }],
config: {},
emitFontFile: () => '/_next/static/fonts/my-font.woff2',
resolve: jest.fn(),
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'my-font';
src: url(/_next/static/fonts/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 100 900;
font-style: italic;
}"
`)
})
test('Other properties', async () => {
const { css } = await loader({
functionName: '',
data: [
{
src: './my-font.woff2',
weight: '100 900',
style: 'italic',
ascentOverride: 'ascentOverride',
descentOverride: 'descentOverride',
lineGapOverride: 'lineGapOverride',
fontStretch: 'fontStretch',
fontFeatureSettings: 'fontFeatureSettings',
sizeAdjust: 'sizeAdjust',
},
],
config: {},
emitFontFile: () => '/_next/static/fonts/my-font.woff2',
resolve: jest.fn(),
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'my-font';
src: url(/_next/static/fonts/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 100 900;
font-style: italic;
ascent-override: ascentOverride;
descent-override: descentOverride;
line-gap-override: lineGapOverride;
font-stretch: fontStretch;
font-feature-settings: fontFeatureSettings;
size-adjust: sizeAdjust;
}"
`)
})
test('Multiple files', async () => {
const { css } = await loader({
functionName: '',
data: [
{
src: [
{ file: './my-font1.woff', unicodeRange: '1' },
{ file: './my-font2.woff2', unicodeRange: '2' },
{ file: './my-font3.eot', unicodeRange: '3' },
{ file: './my-font4.ttf', unicodeRange: '4' },
{ file: './my-font5.otf', unicodeRange: '5' },
],
},
],
config: {},
emitFontFile: () => `/_next/static/fonts/font-file`,
resolve: jest.fn(),
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'my-font1';
src: url(/_next/static/fonts/font-file) format('woff');
font-display: optional;
unicode-range: 1;
}
@font-face {
font-family: 'my-font1';
src: url(/_next/static/fonts/font-file) format('woff2');
font-display: optional;
unicode-range: 2;
}
@font-face {
font-family: 'my-font1';
src: url(/_next/static/fonts/font-file) format('embedded-opentype');
font-display: optional;
unicode-range: 3;
}
@font-face {
font-family: 'my-font1';
src: url(/_next/static/fonts/font-file) format('truetype');
font-display: optional;
unicode-range: 4;
}
@font-face {
font-family: 'my-font1';
src: url(/_next/static/fonts/font-file) format('opentype');
font-display: optional;
unicode-range: 5;
}"
`)
})
})
describe('Errors', () => {
test('Not using default export', async () => {
await expect(
loader({
functionName: 'Named',
data: [],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"@next/font/local has no named exports"`
)
})
test('Invalid file extension', async () => {
await expect(
loader({
functionName: '',
data: [{ src: './font/font-file.abc' }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn().mockResolvedValue(''),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unexpected file \`./font/font-file.abc\`"`
)
})
test('Invalid display value', async () => {
await expect(
loader({
functionName: '',
data: [{ src: './font-file.woff2', display: 'invalid' }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid display value \`invalid\`.
Available display values: \`auto\`, \`block\`, \`swap\`, \`fallback\`, \`optional\`"
`)
})
test('Empty src array', async () => {
await expect(
loader({
functionName: '',
data: [{ src: [] }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Src must contain one or more files"`
)
})
test('Src array must have one or more elements', async () => {
await expect(
loader({
functionName: '',
data: [{ src: [] }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Src must contain one or more files"`
)
})
test('Src array elements must have file property', async () => {
await expect(
loader({
functionName: '',
data: [
{
src: [
{ file: './my-font1.woff2', unicodeRange: '1' },
{ unicodeRange: '2' },
],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Src array objects must have a \`file\` property"`
)
})
test("Src array files must have unicodeRange if there's many files", async () => {
await expect(
loader({
functionName: '',
data: [
{
src: [
{ file: './my-font1.woff2', unicodeRange: '1' },
{ file: './my-font2.woff2' },
],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Files must have a unicode-range if there's more than one"`
)
})
})
})
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