Unverified Commit 3bf29d03 authored by David Ilie's avatar David Ilie Committed by GitHub

Report missing root layouts in webpack

parent ba9f073c
...@@ -13,8 +13,6 @@ import type { ModuleTuple, CollectedMetadata } from '../metadata/types' ...@@ -13,8 +13,6 @@ import type { ModuleTuple, CollectedMetadata } from '../metadata/types'
import path from 'path' import path from 'path'
import { bold } from '../../../../lib/picocolors' import { bold } from '../../../../lib/picocolors'
import { getModuleBuildInfo } from '../get-module-build-info' import { getModuleBuildInfo } from '../get-module-build-info'
import { verifyRootLayout } from '../../../../lib/verify-root-layout'
import * as Log from '../../../output/log'
import { APP_DIR_ALIAS } from '../../../../lib/constants' import { APP_DIR_ALIAS } from '../../../../lib/constants'
import { import {
createMetadataExportsCode, createMetadataExportsCode,
...@@ -57,8 +55,6 @@ export type AppLoaderOptions = { ...@@ -57,8 +55,6 @@ export type AppLoaderOptions = {
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
pageExtensions: PageExtensions pageExtensions: PageExtensions
assetPrefix: string assetPrefix: string
rootDir?: string
tsconfigPath?: string
isDev?: true isDev?: true
basePath: string basePath: string
nextConfigOutput?: NextConfig['output'] nextConfigOutput?: NextConfig['output']
...@@ -681,8 +677,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -681,8 +677,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
allNormalizedAppPaths: allNormalizedAppPathsOption, allNormalizedAppPaths: allNormalizedAppPathsOption,
pagePath, pagePath,
pageExtensions, pageExtensions,
rootDir,
tsconfigPath,
isDev, isDev,
nextConfigOutput, nextConfigOutput,
preferredRegion, preferredRegion,
...@@ -1011,7 +1005,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1011,7 +1005,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
}) })
} }
let treeCodeResult = await createTreeCodeFromPath(pagePath, { const treeCodeResult = await createTreeCodeFromPath(pagePath, {
page, page,
resolveDir, resolveDir,
resolver, resolver,
...@@ -1035,60 +1029,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1035,60 +1029,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const isAppErrorRoute = page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY const isAppErrorRoute = page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
if (!treeCodeResult.rootLayout && !isGlobalNotFoundPath && !isAppErrorRoute) { if (!treeCodeResult.rootLayout && !isGlobalNotFoundPath && !isAppErrorRoute) {
if (!isDev) {
// If we're building and missing a root layout, exit the build
Log.error(
`${bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. To fix this error, make sure every page has a root layout.`
)
process.exit(1)
} else {
// In dev we'll try to create a root layout
const [createdRootLayout, rootLayoutPath] = await verifyRootLayout({
appDir: appDir,
dir: rootDir!,
tsconfigPath: tsconfigPath,
pagePath,
pageExtensions,
})
if (!createdRootLayout) {
let message = `${bold( let message = `${bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '') pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. ` )} doesn't have a root layout. `
message += 'To fix this error, make sure every page has a root layout.'
if (rootLayoutPath) {
message += `We tried to create ${bold(
path.relative(this._compiler?.context ?? '', rootLayoutPath)
)} for you but something went wrong.`
} else {
message +=
'To fix this error, make sure every page has a root layout.'
}
throw new Error(message) throw new Error(message)
} }
// Clear fs cache, get the new result with the created root layout.
if (this._compilation) filesInDirMapMap.get(this._compilation)?.clear()
treeCodeResult = await createTreeCodeFromPath(pagePath, {
page,
resolveDir,
resolver,
metadataResolver,
resolveParallelSegments,
hasChildRoutesForSegment,
getStaticSiblingSegments,
loaderContext: this,
pageExtensions,
basePath,
collectedDeclarations,
isGlobalNotFoundEnabled,
isDev: !!isDev,
})
}
}
const pathname = new AppPathnameNormalizer().normalize(page) const pathname = new AppPathnameNormalizer().normalize(page)
// Prefer to modify next/src/server/app-render/entry-base.ts since this is shared with Turbopack. // Prefer to modify next/src/server/app-render/entry-base.ts since this is shared with Turbopack.
......
import path from 'path'
import * as Log from '../build/output/log'
import { promises as fs } from 'fs'
import { bold } from './picocolors'
import { APP_DIR_ALIAS } from './constants'
import type { PageExtensions } from '../build/page-extensions-type'
const globOrig =
require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')
const glob = (cwd: string, pattern: string): Promise<string[]> => {
return new Promise((resolve, reject) => {
globOrig(pattern, { cwd }, (err, files) => {
if (err) {
return reject(err)
}
resolve(files)
})
})
}
function getRootLayout(isTs: boolean) {
if (isTs) {
return `export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
`
}
return `export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
`
}
export async function verifyRootLayout({
dir,
appDir,
tsconfigPath,
pagePath,
pageExtensions,
}: {
dir: string
appDir: string
tsconfigPath: string | undefined
pagePath: string
pageExtensions: PageExtensions
}): Promise<[boolean, string | undefined]> {
let rootLayoutPath: string | undefined
try {
const layoutFiles = await glob(
appDir,
`**/layout.{${pageExtensions.join(',')}}`
)
const isFileUnderAppDir = pagePath.startsWith(`${APP_DIR_ALIAS}/`)
const normalizedPagePath = pagePath.replace(`${APP_DIR_ALIAS}/`, '')
const pagePathSegments = normalizedPagePath.split('/')
// Find an available dir to place the layout file in, the layout file can't affect any other layout.
// Place the layout as close to app/ as possible.
let availableDir: string | undefined
if (isFileUnderAppDir) {
if (layoutFiles.length === 0) {
// If there's no other layout file we can place the layout file in the app dir.
// However, if the page is within a route group directly under app (e.g. app/(routegroup)/page.js)
// prefer creating the root layout in that route group.
const firstSegmentValue = pagePathSegments[0]
availableDir = firstSegmentValue.startsWith('(')
? firstSegmentValue
: ''
} else {
pagePathSegments.pop() // remove the page from segments
let currentSegments: string[] = []
for (const segment of pagePathSegments) {
currentSegments.push(segment)
// Find the dir closest to app/ where a layout can be created without affecting other layouts.
if (
!layoutFiles.some((file) =>
file.startsWith(currentSegments.join('/'))
)
) {
availableDir = currentSegments.join('/')
break
}
}
}
} else {
availableDir = ''
}
if (typeof availableDir === 'string') {
const tsConfigFileName = tsconfigPath || 'tsconfig.json'
const resolvedTsConfigPath = path.join(dir, tsConfigFileName)
const hasTsConfig = await fs.access(resolvedTsConfigPath).then(
() => true,
() => false
)
rootLayoutPath = path.join(
appDir,
availableDir,
`layout.${hasTsConfig ? 'tsx' : 'js'}`
)
await fs.writeFile(rootLayoutPath, getRootLayout(hasTsConfig))
Log.warn(
`Your page ${bold(
`app/${normalizedPagePath}`
)} did not have a root layout. We created ${bold(
`app${rootLayoutPath.replace(appDir, '')}`
)} for you.`
)
// Created root layout
return [true, rootLayoutPath]
}
} catch (e) {
console.error(e)
}
// Didn't create root layout
return [false, rootLayoutPath]
}
...@@ -1040,9 +1040,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1040,9 +1040,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
), ),
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
rootDir: this.dir,
isDev: true, isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath,
basePath: this.config.basePath, basePath: this.config.basePath,
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
...@@ -1164,9 +1162,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1164,9 +1162,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
pagePath, pagePath,
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
rootDir: this.dir,
isDev: true, isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath,
basePath: this.config.basePath, basePath: this.config.basePath,
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
......
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p id="page-text">Hello world</p>
}
export default function Page() {
return <p id="page-text">Hello world</p>
}
export default function Page() {
return <p id="page-text">Hello world</p>
}
import path from 'path' import path from 'path'
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
// Skip on Turbopack because the user should create the layout manually describe('app-dir missing root layout', () => {
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'app-dir create root layout',
() => {
const isDev = (global as any).isNextDev
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
if (isDev) {
describe('page.js', () => {
describe('root layout in app', () => {
const { next } = nextTestSetup({
files: {
app: new FileRef(path.join(__dirname, 'app')),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/route')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world!'
)
await check(
() => stripAnsi(next.cliOutput.slice(outputIndex)),
/did not have a root layout/
)
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toMatch(
'Your page app/route/page.js did not have a root layout. We created app/layout.js for you.'
)
expect(await next.readFile('app/layout.js')).toMatchInlineSnapshot(`
"export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
"
`)
})
})
describe('root layout in route group', () => {
const { next } = nextTestSetup({
files: {
app: new FileRef(path.join(__dirname, 'app-group-layout')),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world'
)
await check(
() => stripAnsi(next.cliOutput.slice(outputIndex)),
/did not have a root layout/
)
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toInclude(
'Your page app/(group)/page.js did not have a root layout. We created app/(group)/layout.js for you.'
)
expect(await next.readFile('app/(group)/layout.js'))
.toMatchInlineSnapshot(`
"export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
"
`)
})
})
describe('find available dir', () => {
const { next } = nextTestSetup({
files: {
app: new FileRef(path.join(__dirname, 'app-find-available-dir')),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/route/second/inner')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world'
)
await check(
() => stripAnsi(next.cliOutput.slice(outputIndex)),
/did not have a root layout/
)
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toInclude(
'Your page app/(group)/route/second/inner/page.js did not have a root layout. We created app/(group)/route/second/layout.js for you.'
)
expect(await next.readFile('app/(group)/route/second/layout.js'))
.toMatchInlineSnapshot(`
"export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
"
`)
})
})
})
describe('page.tsx', () => {
const { next } = nextTestSetup({
files: {
'app/page.tsx': new FileRef(
path.join(__dirname, 'app/route/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world!'
)
await check(
() => stripAnsi(next.cliOutput.slice(outputIndex)),
/did not have a root layout/
)
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toInclude(
'Your page app/page.tsx did not have a root layout. We created app/layout.tsx for you.'
)
expect(await next.readFile('app/layout.tsx')).toMatchInlineSnapshot(`
"export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
"
`)
})
})
} else {
describe('build', () => {
const { next } = nextTestSetup({
skipStart: true,
files: {
'app/page.js': new FileRef(
path.join(__dirname, 'app/route/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
it('should break the build if a page is missing root layout', async () => {
await expect(next.start()).rejects.toThrow('next build failed')
expect(stripAnsi(next.cliOutput)).toInclude(
"page.js doesn't have a root layout. To fix this error, make sure every page has a root layout."
)
})
})
}
}
)
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'app-dir missing root layout',
() => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
files: { files: {
app: new FileRef(path.join(__dirname, 'app')), app: new FileRef(path.join(__dirname, 'app')),
...@@ -259,5 +36,4 @@ import stripAnsi from 'strip-ansi' ...@@ -259,5 +36,4 @@ import stripAnsi from 'strip-ansi'
expect(await next.hasFile('app/layout.js')).toBe(false) expect(await next.hasFile('app/layout.js')).toBe(false)
}) })
} })
)
...@@ -360,7 +360,6 @@ async function readNormalizedNFT(next, name) { ...@@ -360,7 +360,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/typescript/writeConfigurationDefaults.js", "/node_modules/next/dist/lib/typescript/writeConfigurationDefaults.js",
"/node_modules/next/dist/lib/url.js", "/node_modules/next/dist/lib/url.js",
"/node_modules/next/dist/lib/verify-partytown-setup.js", "/node_modules/next/dist/lib/verify-partytown-setup.js",
"/node_modules/next/dist/lib/verify-root-layout.js",
"/node_modules/next/dist/lib/verify-typescript-setup.js", "/node_modules/next/dist/lib/verify-typescript-setup.js",
"/node_modules/next/dist/lib/wait.js", "/node_modules/next/dist/lib/wait.js",
"/node_modules/next/dist/lib/with-promise-cache.js", "/node_modules/next/dist/lib/with-promise-cache.js",
......
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