Skip to content

Commit

Permalink
Merge pull request #25045 from storybookjs/valentin/nextjs-fix-local-…
Browse files Browse the repository at this point in the history
…font-issue

Next.js: Fix next/font/local usage in babel mode
  • Loading branch information
valentinpalkovic authored Nov 29, 2023
2 parents dbc4f02 + cc9ccee commit aebcbee
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@ import type { LoaderOptions } from '../types';

type LocalFontSrc = string | Array<{ path: string; weight?: string; style?: string }>;

export async function getFontFaceDeclarations(options: LoaderOptions, rootContext: string) {
export async function getFontFaceDeclarations(
options: LoaderOptions,
rootContext: string,
swcMode: boolean
) {
const localFontSrc = options.props.src as LocalFontSrc;

// Parent folder relative to the root context
const parentFolder = path
.dirname(path.join(getProjectRoot(), options.filename))
.replace(rootContext, '');
const parentFolder = swcMode
? path.dirname(path.join(getProjectRoot(), options.filename)).replace(rootContext, '')
: path.dirname(options.filename).replace(rootContext, '');

const { validateData } = require('../utils/local-font-utils');
const { weight, style, variable } = validateData('', options.props);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type FontFaceDeclaration = {

export default async function storybookNextjsFontLoader(this: any) {
const loaderOptions = this.getOptions() as LoaderOptions;
let swcMode = false;
let options;

if (Object.keys(loaderOptions).length > 0) {
Expand All @@ -23,6 +24,7 @@ export default async function storybookNextjsFontLoader(this: any) {
} else {
// handles SWC mode
const importQuery = JSON.parse(this.resourceQuery.slice(1));
swcMode = true;

options = {
filename: importQuery.path,
Expand All @@ -42,7 +44,7 @@ export default async function storybookNextjsFontLoader(this: any) {
}

if (options.source.endsWith('next/font/local') || options.source.endsWith('@next/font/local')) {
fontFaceDeclaration = await getLocalFontFaceDeclarations(options, rootCtx);
fontFaceDeclaration = await getLocalFontFaceDeclarations(options, rootCtx, swcMode);
}

if (typeof fontFaceDeclaration !== 'undefined') {
Expand Down

0 comments on commit aebcbee

Please sign in to comment.