Skip to content

Commit

Permalink
Support for named slots in type checking (#43906)
Browse files Browse the repository at this point in the history
Follow up to #43903, this PR adds named slots to the generated typings,
and provides better error messages for `next build`.

For example, a layout can have `test` as a prop because it has `@test`
co-located. But `invalid` is not a possible prop here:

![CleanShot 2022-12-09 at 21 24
21@2x](https://user-images.githubusercontent.com/3676859/206790150-0e2d7905-fad8-4b26-86ee-d5e69a5ad0f9.png)

And here's the error when running `next build`:

<img width="651" alt="CleanShot 2022-12-09 at 21 21 11@2x"
src="https://user-images.githubusercontent.com/3676859/206789969-8bbd75bd-e7e3-4109-9e0d-d5f8f9a4bbb5.png">

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/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`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
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`](https://github.com/vercel/next.js/blob/canary/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)
  • Loading branch information
shuding committed Dec 9, 2022
1 parent 833a9af commit 8ded797
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
32 changes: 28 additions & 4 deletions packages/next/build/webpack/plugins/flight-types-plugin.ts
@@ -1,4 +1,5 @@
import path from 'path'
import { promises as fs } from 'fs'

import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { WEBPACK_LAYERS } from '../../../lib/constants'
Expand All @@ -17,6 +18,7 @@ function createTypeGuardFile(
relativePath: string,
options: {
type: 'layout' | 'page'
slots?: string[]
}
) {
return `// File: ${fullPath}
Expand All @@ -32,6 +34,11 @@ interface PageProps {
}
interface LayoutProps {
children: React.ReactNode
${
options.slots
? options.slots.map((slot) => ` ${slot}: React.ReactNode`).join('\n')
: ''
}
params: any
}
Expand Down Expand Up @@ -68,6 +75,18 @@ type NonNegative<T extends Numeric> = T extends Zero ? T : Negative<T> extends n
`
}

async function collectNamedSlots(layoutPath: string) {
const layoutDir = path.dirname(layoutPath)
const items = await fs.readdir(layoutDir, { withFileTypes: true })
const slots = []
for (const item of items) {
if (item.isDirectory() && item.name.startsWith('@')) {
slots.push(item.name.slice(1))
}
}
return slots
}

export class FlightTypesPlugin {
dir: string
appDir: string
Expand All @@ -84,7 +103,7 @@ export class FlightTypesPlugin {
apply(compiler: webpack.Compiler) {
const assetPrefix = this.dev ? '..' : this.isEdgeServer ? '..' : '../..'

const handleModule = (_mod: webpack.Module, assets: any) => {
const handleModule = async (_mod: webpack.Module, assets: any) => {
if (_mod.layer !== WEBPACK_LAYERS.server) return
const mod: webpack.NormalModule = _mod as any

Expand All @@ -111,9 +130,11 @@ export class FlightTypesPlugin {
const assetPath = assetPrefix + '/' + typePath.replace(/\\/g, '/')

if (IS_LAYOUT) {
const slots = await collectNamedSlots(mod.resource)
assets[assetPath] = new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'layout',
slots,
})
) as unknown as webpack.sources.RawSource
} else if (IS_PAGE) {
Expand All @@ -126,19 +147,22 @@ export class FlightTypesPlugin {
}

compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
compilation.hooks.processAssets.tapAsync(
{
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets) => {
async (assets, callback) => {
const promises: Promise<any>[] = []
for (const entrypoint of compilation.entrypoints.values()) {
for (const chunk of entrypoint.chunks) {
compilation.chunkGraph.getChunkModules(chunk).forEach((mod) => {
handleModule(mod, assets)
promises.push(handleModule(mod, assets))
})
}
}
await Promise.all(promises)
callback()
}
)
})
Expand Down
16 changes: 13 additions & 3 deletions packages/next/lib/typescript/diagnosticFormatter.ts
Expand Up @@ -103,14 +103,24 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
}
break
case 2741:
const incompatProp = item.messageText.match(
const incompatPageProp = item.messageText.match(
/Property '(.+)' is missing in type 'PageProps'/
)
if (incompatProp) {
if (incompatPageProp) {
main += '\n' + ' '.repeat(indent * 2)
main += `Prop "${chalk.bold(
incompatProp[1]
incompatPageProp[1]
)}" will never be passed. Remove it from the component's props.`
} else {
const extraLayoutProp = item.messageText.match(
/Property '(.+)' is missing in type 'LayoutProps' but required in type '(.+)'/
)
if (extraLayoutProp) {
main += '\n' + ' '.repeat(indent * 2)
main += `Prop "${chalk.bold(
extraLayoutProp[1]
)}" is not valid for this Layout, remove it to fix.`
}
}
break
default:
Expand Down

0 comments on commit 8ded797

Please sign in to comment.