Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Next.js bootup compilation #50379

Merged
merged 17 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/next/src/build/analysis/get-page-static-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export interface PageStaticInfo {
ssr?: boolean
rsc?: RSCModuleType
middleware?: Partial<MiddlewareConfig>
amp?: boolean | 'hybrid'
}

const CLIENT_MODULE_LABEL =
Expand Down Expand Up @@ -488,6 +489,7 @@ export async function getPageStaticInfo(params: {
ssr,
ssg,
rsc,
amp: config.amp || false,
...(middlewareConfig && { middleware: middlewareConfig }),
...(resolvedRuntime && { runtime: resolvedRuntime }),
preferredRegion,
Expand All @@ -498,6 +500,7 @@ export async function getPageStaticInfo(params: {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
amp: false,
runtime: undefined,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ export class ClientReferenceEntryPlugin {
continue
}

if (clientImports.length === 0 && actionImports.length === 0) {
continue
}

const relativeRequest = isAbsoluteRequest
? path.relative(compilation.options.context, entryRequest)
: entryRequest
Expand Down
39 changes: 38 additions & 1 deletion packages/next/src/server/dev/hot-reloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ function erroredPages(compilation: webpack.Compilation) {
}

export default class HotReloader {
private hasAmpEntrypoints: boolean
private hasAppRouterEntrypoints: boolean
private hasPagesRouterEntrypoints: boolean
private dir: string
private buildId: string
private interceptors: any[]
Expand Down Expand Up @@ -223,6 +226,9 @@ export default class HotReloader {
telemetry: Telemetry
}
) {
this.hasAmpEntrypoints = false
this.hasAppRouterEntrypoints = false
this.hasPagesRouterEntrypoints = false
this.buildId = buildId
this.dir = dir
this.interceptors = []
Expand Down Expand Up @@ -719,6 +725,11 @@ export default class HotReloader {
}
}

// Ensure _error is considered a `pages` page.
if (page === '/_error') {
this.hasPagesRouterEntrypoints = true
}

const hasAppDir = !!this.appDir
const isAppPath = hasAppDir && bundlePath.startsWith('app/')
const staticInfo = isEntry
Expand All @@ -732,6 +743,10 @@ export default class HotReloader {
page,
})
: {}

if (staticInfo.amp === true || staticInfo.amp === 'hybrid') {
this.hasAmpEntrypoints = true
}
const isServerComponent =
isAppPath && staticInfo.rsc !== RSC_MODULE_TYPES.client

Expand All @@ -740,6 +755,14 @@ export default class HotReloader {
: entryData.bundlePath.startsWith('app/')
? 'app'
: 'root'

if (pageType === 'pages') {
this.hasPagesRouterEntrypoints = true
}
if (pageType === 'app') {
this.hasAppRouterEntrypoints = true
}

await runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
Expand Down Expand Up @@ -879,6 +902,21 @@ export default class HotReloader {
})
})
)

if (!this.hasAmpEntrypoints) {
delete entrypoints.amp
}
if (!this.hasPagesRouterEntrypoints) {
delete entrypoints.main
delete entrypoints['pages/_app']
delete entrypoints['pages/_error']
delete entrypoints['/_error']
delete entrypoints['pages/_document']
}
if (!this.hasAppRouterEntrypoints) {
delete entrypoints['main-app']
}

return entrypoints
}
}
Expand Down Expand Up @@ -1082,7 +1120,6 @@ export default class HotReloader {
const documentChunk = compilation.namedChunks.get('pages/_document')
// If the document chunk can't be found we do nothing
if (!documentChunk) {
console.warn('_document.js chunk not found')
return
}

Expand Down
83 changes: 39 additions & 44 deletions test/development/next-font/build-errors.test.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,20 @@
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { createNextDescribe } from 'e2e-utils'
import { join } from 'path'
import webdriver from 'next-webdriver'
import { getRedboxSource, hasRedbox } from 'next-test-utils'

describe('build-errors', () => {
let next: NextInstance
createNextDescribe(
'build-errors',
{
files: join(__dirname, 'build-errors'),
},
({ next }) => {
it('should show a next/font error when input is wrong', async () => {
const browser = await next.browser('/')
const content = await next.readFile('app/page.js')

beforeAll(async () => {
next = await createNext({
files: new FileRef(join(__dirname, 'build-errors')),
})
})
afterAll(() => next.destroy())

it('should show a next/font error when input is wrong', async () => {
const browser = await webdriver(next.url, '/')
const content = await next.readFile('app/page.js')

await next.patchFile(
'app/page.js',
`
await next.patchFile(
'app/page.js',
`
import localFont from 'next/font/local'

const font = localFont()
Expand All @@ -29,26 +23,26 @@ export default function Page() {
return <p className={font.className}>Hello world!</p>
}
`
)
)

expect(await hasRedbox(browser, true)).toBeTrue()
expect(await getRedboxSource(browser)).toMatchInlineSnapshot(`
expect(await hasRedbox(browser, true)).toBeTrue()
expect(await getRedboxSource(browser)).toMatchInlineSnapshot(`
"app/page.js
\`next/font\` error:
Missing required \`src\` property"
`)

await next.patchFile('app/page.js', content)
expect(await hasRedbox(browser, false)).toBeFalse()
})
await next.patchFile('app/page.js', content)
expect(await hasRedbox(browser, false)).toBeFalse()
})

it("should show a module not found error if local font file can' be resolved", async () => {
const browser = await webdriver(next.url, '/')
const content = await next.readFile('app/page.js')
it("should show a module not found error if local font file can' be resolved", async () => {
const browser = await next.browser('/')
const content = await next.readFile('app/page.js')

await next.patchFile(
'app/page.js',
`
await next.patchFile(
'app/page.js',
`
import localFont from 'next/font/local'

const font = localFont({ src: './boom.woff2'})
Expand All @@ -57,19 +51,20 @@ export default function Page() {
return <p className={font.className}>Hello world!</p>
}
`
)
)

expect(await hasRedbox(browser, true)).toBeTrue()
const sourceLines = (await getRedboxSource(browser)).split('\n')
expect(await hasRedbox(browser, true)).toBeTrue()
const sourceLines = (await getRedboxSource(browser)).split('\n')

// Should display the file name correctly
expect(sourceLines[0]).toEqual('app/page.js')
// Should be module not found error
expect(sourceLines[1]).toEqual(
"Module not found: Can't resolve './boom.woff2'"
)
// Should display the file name correctly
expect(sourceLines[0]).toEqual('app/page.js')
// Should be module not found error
expect(sourceLines[1]).toEqual(
"Module not found: Can't resolve './boom.woff2'"
)

await next.patchFile('app/page.js', content)
expect(await hasRedbox(browser, false)).toBeFalse()
})
})
await next.patchFile('app/page.js', content)
expect(await hasRedbox(browser, false)).toBeFalse()
})
}
)
9 changes: 7 additions & 2 deletions test/lib/create-next-install.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { linkPackages } =
require('../../.github/actions/next-stats-action/src/prepare/repo-setup')()

async function createNextInstall({
name = '',
parentSpan = null,
dependencies = null,
installCommand = null,
Expand All @@ -23,7 +24,9 @@ async function createNextInstall({
const origRepoDir = path.join(__dirname, '../../')
const installDir = path.join(
tmpDir,
`next-install-${randomBytes(32).toString('hex')}${dirSuffix}`
`next-install${
name ? `-${name.toLowerCase().replace(/ /g, '-')}` : ''
ijjk marked this conversation as resolved.
Show resolved Hide resolved
}-${randomBytes(32).toString('hex')}${dirSuffix}`
)
let tmpRepoDir
require('console').log('Creating next instance in:')
Expand All @@ -37,7 +40,9 @@ async function createNextInstall({
} else {
tmpRepoDir = path.join(
tmpDir,
`next-repo-${randomBytes(32).toString('hex')}${dirSuffix}`
`next-repo${
name ? `-${name.toLowerCase().replace(/ /g, '-')}` : ''
}-${randomBytes(32).toString('hex')}${dirSuffix}`
)
require('console').log('Creating temp repo dir', tmpRepoDir)

Expand Down
1 change: 1 addition & 0 deletions test/lib/e2e-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ export function createNextDescribe(
next: NextInstance
}) => void
): void {
options.name = name
describe(name, () => {
if (options.skipDeployment) {
// When the environment is running for deployment tests.
Expand Down
10 changes: 7 additions & 3 deletions test/lib/next-modes/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export type PackageJson = {
[key: string]: unknown
}
export interface NextInstanceOpts {
name?: string
files: FileRef | string | { [filename: string]: string | FileRef }
dependencies?: { [name: string]: string }
packageJson?: PackageJson
Expand All @@ -47,6 +48,7 @@ type OmitFirstArgument<F> = F extends (
: never

export class NextInstance {
protected name?: string
protected files: FileRef | { [filename: string]: string | FileRef }
protected nextConfig?: NextConfig
protected installCommand?: InstallCommand
Expand Down Expand Up @@ -120,6 +122,7 @@ export class NextInstance {
skipInstall?: boolean
parentSpan: Span
}) {
const name = this.name
if (this.isDestroyed) {
throw new Error('next instance already destroyed')
}
Expand All @@ -134,9 +137,9 @@ export class NextInstance {
: process.env.NEXT_TEST_DIR || (await fs.realpath(os.tmpdir()))
this.testDir = path.join(
tmpDir,
`next-test-${Date.now()}-${(Math.random() * 1000) | 0}${
this.dirSuffix
}`
`next-test${
name ? `-${name.toLowerCase().replace(/ /g, '-')}` : ''
}-${Date.now()}-${(Math.random() * 1000) | 0}${this.dirSuffix}`
)

const reactVersion = process.env.NEXT_TEST_REACT_VERSION || 'latest'
Expand Down Expand Up @@ -190,6 +193,7 @@ export class NextInstance {
await fs.copy(process.env.NEXT_TEST_STARTER, this.testDir)
} else if (!skipIsolatedNext) {
this.testDir = await createNextInstall({
name: this.name,
parentSpan: rootSpan,
dependencies: finalDependencies,
installCommand: this.installCommand,
Expand Down