Unverified Commit 907f3797 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

perf: enable webpack build worker (#57346)

This PR enables the `experimental.webpackBuildWorker` to be on by
default. This flag enables logic inside Next.js to run the compilation
in an isolated worker. The reason for this is that the webpack
compilation process retains a lot of memory for the whole duration of
the build process because it uses some packages that leak. We don't need
it for the rest of the process so it's best to use it in a worker and
leave the memory to be used for static generation.

This will improve memory usage during build, avoiding OOMs caused by
webpack exceeding memory.


<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 63b7b909
---
title: Webpack Build Worker automatic opt-out
---
## Webpack Build Worker Opt-out
#### Why This Error Occurred
The Next.js config contains custom webpack configuration, as a result, the webpack build worker optimization was disabled.
The webpack build worker optimization helps alleviate memory stress during builds and reduce out-of-memory errors although some custom configurations may not be compatible.
#### Possible Ways to Fix It
You can force enable the option by setting &#x60;config.experimental.webpackBuildWorker: true&#x60; in the config.
...@@ -1059,16 +1059,30 @@ export default async function build( ...@@ -1059,16 +1059,30 @@ export default async function build(
}) })
const [duration] = process.hrtime(turboNextBuildStart) const [duration] = process.hrtime(turboNextBuildStart)
return { duration, buildTraceContext: null } return { duration, buildTraceContext: undefined }
} }
let buildTraceContext: undefined | BuildTraceContext let buildTraceContext: undefined | BuildTraceContext
let buildTracesPromise: Promise<any> | undefined = undefined let buildTracesPromise: Promise<any> | undefined = undefined
// if the option is set, we respect it, otherwise we check if the user
// has a custom webpack config and disable the build worker by default.
const useBuildWorker =
config.experimental.webpackBuildWorker || !config.webpack
if (
config.webpack &&
config.experimental.webpackBuildWorker === undefined
) {
Log.warn(
'Custom webpack configuration is detected. When using a custom webpack configuration, the Webpack build worker is disabled by default. To force enable it, set the "experimental.webpackBuildWorker" option to "true". Read more: https://nextjs.org/docs/messages/webpack-build-worker-opt-out'
)
}
if (!isGenerate) { if (!isGenerate) {
if (isCompile && config.experimental.webpackBuildWorker) { if (isCompile && useBuildWorker) {
let durationInSeconds = 0 let durationInSeconds = 0
await webpackBuild(['server']).then((res) => { await webpackBuild(true, ['server']).then((res) => {
buildTraceContext = res.buildTraceContext buildTraceContext = res.buildTraceContext
durationInSeconds += res.duration durationInSeconds += res.duration
const buildTraceWorker = new Worker( const buildTraceWorker = new Worker(
...@@ -1097,11 +1111,11 @@ export default async function build( ...@@ -1097,11 +1111,11 @@ export default async function build(
}) })
}) })
await webpackBuild(['edge-server']).then((res) => { await webpackBuild(true, ['edge-server']).then((res) => {
durationInSeconds += res.duration durationInSeconds += res.duration
}) })
await webpackBuild(['client']).then((res) => { await webpackBuild(true, ['client']).then((res) => {
durationInSeconds += res.duration durationInSeconds += res.duration
}) })
...@@ -1117,7 +1131,7 @@ export default async function build( ...@@ -1117,7 +1131,7 @@ export default async function build(
} else { } else {
const { duration: webpackBuildDuration, ...rest } = turboNextBuild const { duration: webpackBuildDuration, ...rest } = turboNextBuild
? await turbopackBuild() ? await turbopackBuild()
: await webpackBuild() : await webpackBuild(false)
buildTraceContext = rest.buildTraceContext buildTraceContext = rest.buildTraceContext
......
...@@ -125,17 +125,16 @@ async function webpackBuildWithWorker( ...@@ -125,17 +125,16 @@ async function webpackBuildWithWorker(
return combinedResult return combinedResult
} }
export async function webpackBuild( export function webpackBuild(
withWorker: boolean,
compilerNames?: typeof ORDERED_COMPILER_NAMES compilerNames?: typeof ORDERED_COMPILER_NAMES
) { ): ReturnType<typeof webpackBuildWithWorker> {
const config = NextBuildContext.config! if (withWorker) {
if (config.experimental.webpackBuildWorker) {
debug('using separate compiler workers') debug('using separate compiler workers')
return await webpackBuildWithWorker(compilerNames) return webpackBuildWithWorker(compilerNames)
} else { } else {
debug('building all compilers in same process') debug('building all compilers in same process')
const webpackBuildImpl = require('./impl').webpackBuildImpl const webpackBuildImpl = require('./impl').webpackBuildImpl
return await webpackBuildImpl() return webpackBuildImpl()
} }
} }
...@@ -282,7 +282,11 @@ export interface ExperimentalConfig { ...@@ -282,7 +282,11 @@ export interface ExperimentalConfig {
typedRoutes?: boolean typedRoutes?: boolean
/** /**
* This option is to enable running the Webpack build in a worker thread. * Run the Webpack build in a separate process to optimize memory usage during build.
* Valid values are:
* - `false`: Disable the Webpack build worker
* - `true`: Enable the Webpack build worker
* - `undefined`: Enable the Webpack build worker only if the webpack config is not customized
*/ */
webpackBuildWorker?: boolean webpackBuildWorker?: boolean
...@@ -771,6 +775,7 @@ export const defaultConfig: NextConfig = { ...@@ -771,6 +775,7 @@ export const defaultConfig: NextConfig = {
typedRoutes: false, typedRoutes: false,
instrumentationHook: false, instrumentationHook: false,
bundlePagesExternals: false, bundlePagesExternals: false,
webpackBuildWorker: undefined,
}, },
} }
......
...@@ -23,7 +23,10 @@ let devOutput ...@@ -23,7 +23,10 @@ let devOutput
() => { () => {
it('should not fail to build invalid usage of the Image component', async () => { it('should not fail to build invalid usage of the Image component', async () => {
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toBeFalsy() const errors = stderr
.split('\n')
.filter((line: string) => line && !line.trim().startsWith('⚠'))
expect(errors).toEqual([])
expect(code).toBe(0) expect(code).toBe(0)
}) })
} }
......
...@@ -25,7 +25,7 @@ let devOutput ...@@ -25,7 +25,7 @@ let devOutput
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
const errors = stderr const errors = stderr
.split('\n') .split('\n')
.filter((line) => line && !line.trim().startsWith('⚠️')) .filter((line: string) => line && !line.trim().startsWith('⚠'))
expect(errors).toEqual([]) expect(errors).toEqual([])
expect(code).toBe(0) expect(code).toBe(0)
}) })
......
...@@ -22,8 +22,10 @@ const appDir = path.join(__dirname, '..') ...@@ -22,8 +22,10 @@ const appDir = path.join(__dirname, '..')
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
console.log(stderr) const errors = stderr
expect(stderr.length).toStrictEqual(0) .split('\n')
.filter((line) => line && !line.trim().startsWith('⚠'))
expect(errors).toEqual([])
expect(stdout).toMatch(/Initialized config/) expect(stdout).toMatch(/Initialized config/)
}) })
}) })
......
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