Unverified Commit 584d842a authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Fix @next/font imports from outside of the root directory (#42678)

Similar to https://github.com/vercel/next.js/pull/42106. Make
`@next/font` works as expected when using `transpilePackages`.

Also makes sure `@next/font` is auto-configured correctly when in a
monorepo.

## 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 build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent c962f2d6
# Babel and Font loader conflict # Babel and `@next/font` conflict
#### Why This Error Occurred #### Why This Error Occurred
You have tried to use `experimental.fontLoaders` with a custom babel config. When your application has a custom babel config you opt-out of the Next.js Compiler which is required to use `experimental.fontLoaders`. You have tried to use `@next/font` with a custom babel config. When your application has a custom babel config you opt-out of the Next.js Compiler which is required to use `@next/font`.
#### Possible Ways to Fix It #### Possible Ways to Fix It
......
...@@ -121,6 +121,10 @@ function getPlugins( ...@@ -121,6 +121,10 @@ function getPlugins(
{ type: 'plugin' } { type: 'plugin' }
) )
: null : null
const nextFontUnsupported = createConfigItem(
[require('../plugins/next-font-unsupported')],
{ type: 'plugin' }
)
return [ return [
reactRefreshItem, reactRefreshItem,
...@@ -130,6 +134,7 @@ function getPlugins( ...@@ -130,6 +134,7 @@ function getPlugins(
transformDefineItem, transformDefineItem,
nextSsgItem, nextSsgItem,
commonJsItem, commonJsItem,
nextFontUnsupported,
].filter(Boolean) ].filter(Boolean)
} }
......
import { NodePath, PluginObj, types } from 'next/dist/compiled/babel/core'
export default function NextPageDisallowReExportAllExports(): PluginObj<any> {
return {
visitor: {
ImportDeclaration(path: NodePath<types.ImportDeclaration>) {
if (
['@next/font/local', '@next/font/google'].includes(
path.node.source.value
)
) {
const err = new SyntaxError(
`"@next/font" requires SWC although Babel is being used due to a custom babel config being present.\nRead more: https://nextjs.org/docs/messages/babel-font-loader-conflict`
)
;(err as any).code = 'BABEL_PARSE_ERROR'
;(err as any).loc =
path.node.loc?.start ?? path.node.loc?.end ?? path.node.loc
throw err
}
},
},
}
}
...@@ -662,16 +662,6 @@ export default async function getBaseWebpackConfig( ...@@ -662,16 +662,6 @@ export default async function getBaseWebpackConfig(
loggedIgnoredCompilerOptions = true loggedIgnoredCompilerOptions = true
} }
if (!useSWCLoader && babelConfigFile && config.experimental.fontLoaders) {
Log.error(
`"experimental.fontLoaders" is enabled which requires SWC although Babel is being used due to custom babel config being present "${path.relative(
dir,
babelConfigFile
)}".\nSee more info here: https://nextjs.org/docs/messages/babel-font-loader-conflict`
)
process.exit(1)
}
const getBabelLoader = () => { const getBabelLoader = () => {
return { return {
loader: require.resolve('./babel/loader/index'), loader: require.resolve('./babel/loader/index'),
......
...@@ -11,7 +11,6 @@ import { ...@@ -11,7 +11,6 @@ import {
getGlobalModuleImportError, getGlobalModuleImportError,
getLocalModuleImportError, getLocalModuleImportError,
getFontLoaderDocumentImportError, getFontLoaderDocumentImportError,
getFontLoaderImportError,
} from './messages' } from './messages'
import { getPostCssPlugins } from './plugins' import { getPostCssPlugins } from './plugins'
...@@ -25,8 +24,6 @@ const regexCssModules = /\.module\.css$/ ...@@ -25,8 +24,6 @@ const regexCssModules = /\.module\.css$/
// RegExps for Syntactically Awesome Style Sheets // RegExps for Syntactically Awesome Style Sheets
const regexSassGlobal = /(?<!\.module)\.(scss|sass)$/ const regexSassGlobal = /(?<!\.module)\.(scss|sass)$/
const regexSassModules = /\.module\.(scss|sass)$/ const regexSassModules = /\.module\.(scss|sass)$/
// Also match the virtual client entry which doesn't have file path
const regexClientEntry = /^$/
/** /**
* Mark a rule as removable if built-in CSS support is disabled * Mark a rule as removable if built-in CSS support is disabled
...@@ -218,35 +215,11 @@ export const css = curry(async function css( ...@@ -218,35 +215,11 @@ export const css = curry(async function css(
markRemovable({ markRemovable({
sideEffects: false, sideEffects: false,
test: fontLoaderPath, test: fontLoaderPath,
issuer: {
and: [
{
or: [ctx.rootDirectory, regexClientEntry],
},
],
not: [/node_modules/],
},
use: getFontLoader(ctx, lazyPostCSSInitializer, fontLoaderOptions), use: getFontLoader(ctx, lazyPostCSSInitializer, fontLoaderOptions),
}), }),
], ],
}) })
) )
fns.push(
loader({
oneOf: [
markRemovable({
test: fontLoaderPath,
use: {
loader: 'error-loader',
options: {
reason: getFontLoaderImportError(),
},
},
}),
],
})
)
}) })
// CSS cannot be imported in _document. This comes before everything because // CSS cannot be imported in _document. This comes before everything because
......
...@@ -37,9 +37,3 @@ export function getFontLoaderDocumentImportError() { ...@@ -37,9 +37,3 @@ export function getFontLoaderDocumentImportError() {
'cannot' 'cannot'
)} be used within ${chalk.cyan('pages/_document.js')}.` )} be used within ${chalk.cyan('pages/_document.js')}.`
} }
export function getFontLoaderImportError() {
return `Font loader error:\nFont loaders ${chalk.bold(
'cannot'
)} be used from within ${chalk.bold('node_modules')}.`
}
...@@ -24,7 +24,6 @@ import { ...@@ -24,7 +24,6 @@ import {
} from '../shared/lib/image-config' } from '../shared/lib/image-config'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { gte as semverGte } from 'next/dist/compiled/semver' import { gte as semverGte } from 'next/dist/compiled/semver'
import { getDependencies } from '../lib/get-package-version'
export { DomainLocale, NextConfig, normalizeConfig } from './config-shared' export { DomainLocale, NextConfig, normalizeConfig } from './config-shared'
...@@ -93,15 +92,17 @@ export function setHttpClientAndAgentOptions(config: { ...@@ -93,15 +92,17 @@ export function setHttpClientAndAgentOptions(config: {
) )
} }
async function setFontLoaderDefaults(config: NextConfigComplete, dir: string) { function setFontLoaderDefaults(config: NextConfigComplete) {
// Add @next/font loaders by default if they're installed try {
const hasNextFontDependency = ( // eslint-disable-next-line import/no-extraneous-dependencies
await getDependencies({ const nextFontVersion = require('@next/font/package.json').version
cwd: dir, const nextVersion = require('next/package.json').version
}) if (nextFontVersion !== nextVersion) {
).dependencies['@next/font'] Log.warn(
`Different versions of @next/font (${nextFontVersion}) and next (${nextVersion}) detected. This may lead to unexpected behavior.`
)
}
if (hasNextFontDependency) {
const googleFontLoader = { const googleFontLoader = {
loader: '@next/font/google', loader: '@next/font/google',
} }
...@@ -128,7 +129,7 @@ async function setFontLoaderDefaults(config: NextConfigComplete, dir: string) { ...@@ -128,7 +129,7 @@ async function setFontLoaderDefaults(config: NextConfigComplete, dir: string) {
) { ) {
config.experimental.fontLoaders.push(localFontLoader) config.experimental.fontLoaders.push(localFontLoader)
} }
} } catch {}
} }
function assignDefaults(dir: string, userConfig: { [key: string]: any }) { function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
...@@ -906,7 +907,7 @@ export default async function loadConfig( ...@@ -906,7 +907,7 @@ export default async function loadConfig(
configFileName, configFileName,
...userConfig, ...userConfig,
}) as NextConfigComplete }) as NextConfigComplete
await setFontLoaderDefaults(completeConfig, dir) setFontLoaderDefaults(completeConfig)
return completeConfig return completeConfig
} else { } else {
const configBaseName = basename(CONFIG_FILES[0], extname(CONFIG_FILES[0])) const configBaseName = basename(CONFIG_FILES[0], extname(CONFIG_FILES[0]))
...@@ -936,6 +937,6 @@ export default async function loadConfig( ...@@ -936,6 +937,6 @@ export default async function loadConfig(
) as NextConfigComplete ) as NextConfigComplete
completeConfig.configFileName = configFileName completeConfig.configFileName = configFileName
setHttpClientAndAgentOptions(completeConfig) setHttpClientAndAgentOptions(completeConfig)
await setFontLoaderDefaults(completeConfig, dir) setFontLoaderDefaults(completeConfig)
return completeConfig return completeConfig
} }
...@@ -30,6 +30,7 @@ describe('app dir - rsc external dependency', () => { ...@@ -30,6 +30,7 @@ describe('app dir - rsc external dependency', () => {
next = await createNext({ next = await createNext({
files: new FileRef(path.join(__dirname, './rsc-external')), files: new FileRef(path.join(__dirname, './rsc-external')),
dependencies: { dependencies: {
'@next/font': 'canary',
react: 'latest', react: 'latest',
'react-dom': 'latest', 'react-dom': 'latest',
swr: '2.0.0-rc.0', swr: '2.0.0-rc.0',
...@@ -155,4 +156,14 @@ describe('app dir - rsc external dependency', () => { ...@@ -155,4 +156,14 @@ describe('app dir - rsc external dependency', () => {
) )
).toBe('rgb(255, 0, 0)') ).toBe('rgb(255, 0, 0)')
}) })
it('should handle external @next/font', async () => {
const browser = await webdriver(next.url, '/font')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('p')).fontFamily`
)
).toMatch(/^__myFont_.{6}, __myFont_Fallback_.{6}$/)
})
}) })
import { myFont } from 'font'
export default function Page() {
return <p className={myFont.className}>Hello world</p>
}
...@@ -3,6 +3,6 @@ module.exports = { ...@@ -3,6 +3,6 @@ module.exports = {
experimental: { experimental: {
appDir: true, appDir: true,
serverComponentsExternalPackages: ['conditional-exports-optout'], serverComponentsExternalPackages: ['conditional-exports-optout'],
transpilePackages: ['untranspiled-module', 'css'], transpilePackages: ['untranspiled-module', 'css', 'font'],
}, },
} }
import localFont from '@next/font/local'
export const myFont = localFont({ src: './my-font.woff2' })
module.exports = {
experimental: {
fontLoaders: [
{
loader: '@next/font/google',
options: { subsets: ['latin'] },
},
],
},
}
...@@ -2,19 +2,13 @@ import { createNext, FileRef } from 'e2e-utils' ...@@ -2,19 +2,13 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base' import { NextInstance } from 'test/lib/next-modes/base'
import { join } from 'path' import { join } from 'path'
describe('@next/font/google babel', () => { describe('@next/fon babel unsupported', () => {
const isNextStart = (global as any).isNextStart
let next: NextInstance let next: NextInstance
if (!isNextStart) {
it('should only run on next start', () => {})
return
}
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
skipStart: true, skipStart: true,
files: new FileRef(join(__dirname, 'babel')), files: new FileRef(join(__dirname, 'babel-unsupported')),
dependencies: { dependencies: {
'@next/font': 'canary', '@next/font': 'canary',
}, },
...@@ -27,7 +21,7 @@ describe('@next/font/google babel', () => { ...@@ -27,7 +21,7 @@ describe('@next/font/google babel', () => {
'next build failed with code/signal 1' 'next build failed with code/signal 1'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
/"experimental.fontLoaders" is enabled which requires SWC although Babel is being used due to custom babel config being present ".babelrc"./ /"@next\/font" requires SWC although Babel is being used due to a custom babel config being present./
) )
}) })
}) })
import { Inter } from '@next/font/google'
console.log(Inter)
export default function Page() { export default function Page() {
return <p>Hello world</p> return <p>Hello world</p>
} }
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