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

Create root layout (#41523)

Creates a root layout if it is missing in DEV when building the page in
`next-app-loader`. If the page is in a route group, the layout will be
created there. Otherwise it will create a layout directly under `/app`.

Breaks the build if a page is found that's missing a root layout.

## 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 0a97d078
...@@ -217,6 +217,9 @@ export function getAppEntry(opts: { ...@@ -217,6 +217,9 @@ export function getAppEntry(opts: {
appDir: string appDir: string
appPaths: string[] | null appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
isDev?: boolean
rootDir?: string
tsconfigPath?: string
}) { }) {
return { return {
import: `next-app-loader?${stringify(opts)}!`, import: `next-app-loader?${stringify(opts)}!`,
......
import type webpack from 'webpack' import type webpack from 'webpack'
import chalk from 'next/dist/compiled/chalk'
import type { ValueOf } from '../../../shared/lib/constants' import type { ValueOf } from '../../../shared/lib/constants'
import { NODE_RESOLVE_OPTIONS } from '../../webpack-config' import { NODE_RESOLVE_OPTIONS } from '../../webpack-config'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { sep } from 'path' import { sep } from 'path'
import { verifyRootLayout } from '../../../lib/verifyRootLayout'
import * as Log from '../../../build/output/log'
import { APP_DIR_ALIAS } from '../../../lib/constants'
export const FILE_TYPES = { export const FILE_TYPES = {
layout: 'layout', layout: 'layout',
...@@ -35,6 +39,7 @@ async function createTreeCodeFromPath({ ...@@ -35,6 +39,7 @@ async function createTreeCodeFromPath({
const splittedPath = pagePath.split(/[\\/]/) const splittedPath = pagePath.split(/[\\/]/)
const appDirPrefix = splittedPath[0] const appDirPrefix = splittedPath[0]
const pages: string[] = [] const pages: string[] = []
let rootLayout: string | undefined
async function createSubtreePropsFromSegmentPath( async function createSubtreePropsFromSegmentPath(
segments: string[] segments: string[]
...@@ -82,6 +87,12 @@ async function createTreeCodeFromPath({ ...@@ -82,6 +87,12 @@ async function createTreeCodeFromPath({
}) })
) )
if (!rootLayout) {
rootLayout = filePaths.find(
([type, path]) => type === 'layout' && !!path
)?.[1]
}
props[parallelKey] = `[ props[parallelKey] = `[
'${parallelSegment}', '${parallelSegment}',
${subtree}, ${subtree},
...@@ -111,7 +122,7 @@ async function createTreeCodeFromPath({ ...@@ -111,7 +122,7 @@ async function createTreeCodeFromPath({
} }
const tree = await createSubtreePropsFromSegmentPath([]) const tree = await createSubtreePropsFromSegmentPath([])
return [`const tree = ${tree}.children;`, pages] return [`const tree = ${tree}.children;`, pages, rootLayout]
} }
function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) { function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) {
...@@ -129,9 +140,20 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -129,9 +140,20 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
appDir: string appDir: string
appPaths: string[] | null appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
rootDir?: string
tsconfigPath?: string
isDev?: boolean
}> = async function nextAppLoader() { }> = async function nextAppLoader() {
const { name, appDir, appPaths, pagePath, pageExtensions } = const {
this.getOptions() || {} name,
appDir,
appPaths,
pagePath,
pageExtensions,
rootDir,
tsconfigPath,
isDev,
} = this.getOptions() || {}
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
buildInfo.route = { buildInfo.route = {
...@@ -182,12 +204,36 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -182,12 +204,36 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
} }
} }
const [treeCode, pages] = await createTreeCodeFromPath({ const [treeCode, pages, rootLayout] = await createTreeCodeFromPath({
pagePath, pagePath,
resolve: resolver, resolve: resolver,
resolveParallelSegments, resolveParallelSegments,
}) })
if (!rootLayout) {
const errorMessage = `${chalk.bold(
pagePath.replace(`${APP_DIR_ALIAS}/`, '')
)} doesn't have a root layout. To fix this error, make sure every page has a root layout.`
if (!isDev) {
// If we're building and missing a root layout, exit the build
Log.error(errorMessage)
process.exit(1)
} else {
// In dev we'll try to create a root layout
const createdRootLayout = await verifyRootLayout({
appDir: appDir,
dir: rootDir!,
tsconfigPath: tsconfigPath!,
pagePath,
pageExtensions,
})
if (!createdRootLayout) {
throw new Error(errorMessage)
}
}
}
const result = ` const result = `
export ${treeCode} export ${treeCode}
export const pages = ${JSON.stringify(pages)} export const pages = ${JSON.stringify(pages)}
......
import * as React from 'react' import React from 'react'
import { import {
Dialog, Dialog,
DialogBody, DialogBody,
...@@ -32,7 +32,7 @@ export const RootLayoutError: React.FC<RootLayoutErrorProps> = ...@@ -32,7 +32,7 @@ export const RootLayoutError: React.FC<RootLayoutErrorProps> =
<DialogContent> <DialogContent>
<DialogHeader className="nextjs-container-root-layout-error-header"> <DialogHeader className="nextjs-container-root-layout-error-header">
<h4 id="nextjs__container_root_layout_error_label"> <h4 id="nextjs__container_root_layout_error_label">
Root layout error Missing required tags
</h4> </h4>
</DialogHeader> </DialogHeader>
<DialogBody className="nextjs-container-root-layout-error-body"> <DialogBody className="nextjs-container-root-layout-error-body">
...@@ -40,8 +40,8 @@ export const RootLayoutError: React.FC<RootLayoutErrorProps> = ...@@ -40,8 +40,8 @@ export const RootLayoutError: React.FC<RootLayoutErrorProps> =
<footer> <footer>
<p id="nextjs__container_root_layout_error_desc"> <p id="nextjs__container_root_layout_error_desc">
<small> <small>
This error occurred during the build process and can only be This error and can only be dismissed by providing all
dismissed by fixing the error. required tags.
</small> </small>
</p> </p>
</footer> </footer>
......
import path from 'path'
import { promises as fs } from 'fs'
import chalk from 'next/dist/compiled/chalk'
import * as Log from '../build/output/log'
import { APP_DIR_ALIAS } from './constants'
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 default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
`
}
return `export default function RootLayout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
`
}
export async function verifyRootLayout({
dir,
appDir,
tsconfigPath,
pagePath,
pageExtensions,
}: {
dir: string
appDir: string
tsconfigPath: string
pagePath: string
pageExtensions: string[]
}) {
try {
const layoutFiles = await glob(
appDir,
`**/layout.{${pageExtensions.join(',')}}`
)
const hasLayout = layoutFiles.length !== 0
const normalizedPagePath = pagePath.replace(`${APP_DIR_ALIAS}/`, '')
const firstSegmentValue = normalizedPagePath.split('/')[0]
const pageRouteGroup = firstSegmentValue.startsWith('(')
? firstSegmentValue
: undefined
if (pageRouteGroup || !hasLayout) {
const resolvedTsConfigPath = path.join(dir, tsconfigPath)
const hasTsConfig = await fs.access(resolvedTsConfigPath).then(
() => true,
() => false
)
const rootLayoutPath = path.join(
appDir,
// 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. Otherwise create the root layout in the app root.
pageRouteGroup ? pageRouteGroup : '',
`layout.${hasTsConfig ? 'tsx' : 'js'}`
)
await fs.writeFile(rootLayoutPath, getRootLayout(hasTsConfig))
console.log(
chalk.green(
`\nYour page ${chalk.bold(
`app/${normalizedPagePath}`
)} did not have a root layout, we created ${chalk.bold(
`app${rootLayoutPath.replace(appDir, '')}`
)} for you.`
) + '\n'
)
// Created root layout
return true
}
} catch (error) {
Log.error('Failed to create root layout', error)
}
// Didn't create root layout
return false
}
...@@ -624,6 +624,9 @@ export default class HotReloader { ...@@ -624,6 +624,9 @@ export default class HotReloader {
), ),
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
rootDir: this.dir,
isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath,
}).import }).import
: undefined : undefined
...@@ -702,6 +705,9 @@ export default class HotReloader { ...@@ -702,6 +705,9 @@ export default class HotReloader {
), ),
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
rootDir: this.dir,
isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath,
}) })
: relativeRequest, : relativeRequest,
hasAppDir, hasAppDir,
......
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import path from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import webdriver from 'next-webdriver'
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 (process.env.NEXT_TEST_REACT_VERSION === '^17') {
it('should skip for react v17', () => {})
return
}
let next: NextInstance
if (isDev) {
describe('page.js', () => {
describe('root layout in app', () => {
beforeAll(async () => {
next = await createNext({
files: {
'app/page.js': new FileRef(
path.join(__dirname, 'create-root-layout/app/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'create-root-layout/next.config.js')
),
},
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
},
})
})
afterAll(() => next.destroy())
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await webdriver(next.url, '/')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world!'
)
expect(next.cliOutput.slice(outputIndex)).toInclude(
'Your page app/page.js did not have a root layout, we created app/layout.js for you.'
)
expect(await next.readFile('app/layout.js')).toMatchInlineSnapshot(`
"export default function RootLayout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
"
`)
})
})
describe('root layout in route group', () => {
beforeAll(async () => {
next = await createNext({
files: {
app: new FileRef(
path.join(__dirname, 'create-root-layout/app-group-layout')
),
'next.config.js': new FileRef(
path.join(__dirname, 'create-root-layout/next.config.js')
),
},
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
},
})
})
afterAll(() => next.destroy())
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await webdriver(next.url, '/path2')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world 2'
)
expect(next.cliOutput.slice(outputIndex)).toInclude(
'Your page app/(group2)/path2/page.js did not have a root layout, we created app/(group2)/layout.js for you.'
)
expect(await next.readFile('app/(group2)/layout.js'))
.toMatchInlineSnapshot(`
"export default function RootLayout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
"
`)
})
})
})
describe('page.tsx', () => {
beforeAll(async () => {
next = await createNext({
files: {
'app/page.tsx': new FileRef(
path.join(__dirname, 'create-root-layout/app/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'create-root-layout/next.config.js')
),
},
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
typescript: 'latest',
'@types/react': 'latest',
'@types/node': 'latest',
},
})
})
afterAll(() => next.destroy())
it('create root layout', async () => {
const outputIndex = next.cliOutput.length
const browser = await webdriver(next.url, '/')
expect(await browser.elementById('page-text').text()).toBe(
'Hello world!'
)
expect(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 default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
"
`)
})
})
} else {
describe('build', () => {
it('should break the build if a page is missing root layout', async () => {
const next = await createNext({
skipStart: true,
files: {
'app/page.js': new FileRef(
path.join(__dirname, 'create-root-layout/app/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'create-root-layout/next.config.js')
),
},
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
},
})
await expect(next.start()).rejects.toThrow('next build failed')
expect(next.cliOutput).toInclude(
"page.js doesn't have a root layout. To fix this error, make sure every page has a root layout."
)
await next.destroy()
})
})
}
})
export default function RootLayout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p id="page-text">Hello world 1</p>
}
export default function Page() {
return <p id="page-text">Hello world 2</p>
}
export default function Page() {
return <p id="page-text">Hello world!</p>
}
module.exports = {
experimental: {
appDir: true,
},
}
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