Unverified Commit e489aae4 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Reland experimental custom webpack support (#99234)

### What?

Reland [#98862](https://github.com/vercel/next.js/pull/98862) after its
revert in [#99227](https://github.com/vercel/next.js/pull/99227).
Restore `next dev --custom-webpack` and `next build --custom-webpack`,
CLI documentation, and the original e2e fixture, **without declaring
webpack as a peer dependency**. `--webpack` continues using bundled
webpack.

### Why?

Allow applications to explicitly opt into their installed webpack
version. The CLI records the absolute application directory before
loading dev/build internals; config loading validates webpack, while
Next.js's compiled webpack wrapper uses a project-scoped `createRequire`
for every webpack import. This ensures `next.config.js`, user plugins,
and Next.js compilation use the same webpack even if a different version
is visible from inside the `next` package. Custom mode installs no
webpack aliases; bundled mode keeps its explicit alias list.

### How?

Restore the feature on post-revert canary without undoing intervening
changes (including `next analyze`). Keep webpack as an
application-installed dependency checked at opt-in time, rather than an
npm peer in `next`'s published metadata. The e2e tests exercise webpack
5.98.0 and 5.111.0 in dev and production, config-time
`require('webpack/package.json')`, custom and built-in plugins, the
missing-install diagnostic, bundled fallback, and conflicting flags. A
regression fixture disables pnpm hoisting and shadows webpack 5.98.0
beside `next` while the app installs 5.111.0; it proves Next still
selects the app's instance. Another test builds with an explicit
application directory from a different cwd. A dedicated Custom Webpack
guide (shared between App and Pages Routers) includes install/usage
examples and a pnpm `hoistPattern` note for plugins and workspace
tooling that independently resolve webpack; both CLI option rows link to
the guide.

**Internal-sync caveat:** #99227 reports that declaring webpack as an
optional peer introduced a dependency chain that duplicated Next.js in
monorepos and broke internal sync. This reland **omits the peer
declaration** to avoid that specific graph edge, while keeping runtime
validation for `--custom-webpack`. The private dependency graph and sync
reproduction are unavailable here; local tests do **not** independently
prove internal sync is fixed. Maintainers should verify it before
merging.

**Local verification:** focused e2e **8/8 dev and 8/8 production** (plus
targeted non-isolated checks for the two new tests), Next.js build and
types, frozen lockfile install, changed-file ESLint, Prettier, and `pnpm
types-and-precompiled` from a clean commit (no generated diff).
Repo-wide `pnpm lint-eslint .` fails with a plugin-scope configuration
error on the post-revert base as well
(`import/no-extraneous-dependencies` cannot find plugin `import`);
changed-file lint passes.

**Review follow-up:** Restored the bundled-only `webpack/package`
metadata alias and added config-time coverage for both extensionless and
`.json` metadata imports. Per sokra's direction, no runtime version
validation is added; the docs explicitly describe custom webpack as use
at your own risk and list the tested versions without guaranteeing
compatibility.

**CI note:** Commit `51ebc4f9` passed docs-link, lint,
types/precompiled, all production tests and changed-test flake runs, but
a new explicit-directory case attempted `next build` inside a dev-mode
shard and failed deterministically with a missing `.next/dev/trace`. The
follow-up test-only commit `9d5c3d4e` instead exercises `next dev
<appDir>` there and checks its HTTP output; it preserves the production
`next build <appDir>` assertion. Focused dev and production e2e tests
pass 8/8 locally; That commit's CI passed. Review follow-up `ed1c7bd0`
also passed CI. The docs-only commit `10cbbd84` moves the setup section
into the dedicated guide; its CI is running. The earlier docs-only
commit also hit unrelated instant-validation snapshot mismatches, which
were not rerun as flakes.

<!-- NEXT_JS_LLM -->


<!-- fleet 19431696-5f4c-400d-a3be-700bfe86abda -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 0541251f
---
title: How to use a custom webpack version in Next.js
nav_title: Custom Webpack
description: Use your application's webpack installation with Next.js instead of the bundled version.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
By default, `--webpack` uses the webpack version bundled with Next.js. To use webpack installed in your application instead, install webpack in your application and pass `--custom-webpack` to `next dev` or `next build`. Run the development and production commands separately; `next dev` keeps running until stopped:
```bash package="pnpm"
pnpm add -D webpack@^5.98.0
pnpm next dev --custom-webpack
pnpm next build --custom-webpack
```
```bash package="npm"
npm install -D webpack@^5.98.0
npx next dev --custom-webpack
npx next build --custom-webpack
```
```bash package="yarn"
yarn add -D webpack@^5.98.0
yarn next dev --custom-webpack
yarn next build --custom-webpack
```
```bash package="bun"
bun add -D webpack@^5.98.0
bunx next dev --custom-webpack
bunx next build --custom-webpack
```
**Use a custom webpack version at your own risk.** Next.js does not validate the installed webpack version, and compatibility with other versions is not guaranteed. The examples use `^5.98.0`; this feature is tested with webpack 5.98.0 and 5.111.0.
Run the install command from your application's directory. The custom version is available when Next.js evaluates `next.config.js`, so your webpack configuration and plugins can import it. If webpack is not installed in the application, `--custom-webpack` reports how to install it.
**Using pnpm with restricted hoisting:** Next.js resolves webpack directly from your application, even when pnpm does not hoist it. However, custom webpack plugins or other workspace tooling may resolve webpack from their own package locations. If they cannot find it because you have restricted pnpm's [hoisting](https://pnpm.io/settings/node-modules#hoistpattern), add `webpack` to your existing `hoistPattern` in the workspace root's `pnpm-workspace.yaml`:
```yaml filename="pnpm-workspace.yaml"
hoistPattern:
- '*eslint*' # Example existing pattern; keep your own patterns.
- webpack
```
Keep any other patterns your project already uses. If you use pnpm's default `hoistPattern` (`['*']`), you do not need this setting. If you have disabled hoisting entirely with `hoist: false`, enable it before using `hoistPattern`. See [pnpm's node-modules settings](https://pnpm.io/settings/node-modules) for details.
...@@ -66,7 +66,8 @@ The following options are available when running `next dev`: ...@@ -66,7 +66,8 @@ The following options are available when running `next dev`:
| `-h, --help` | Show all available options. | | `-h, --help` | Show all available options. |
| `[directory]` | A directory in which to build the application. If not provided, current directory is used. | | `[directory]` | A directory in which to build the application. If not provided, current directory is used. |
| `--turbopack` | Force enable [Turbopack](/docs/app/api-reference/turbopack) (enabled by default). Also available as `--turbo`. | | `--turbopack` | Force enable [Turbopack](/docs/app/api-reference/turbopack) (enabled by default). Also available as `--turbo`. |
| `--webpack` | Use Webpack instead of the default [Turbopack](/docs/app/api-reference/turbopack) bundler for development. | | `--webpack` | Use the bundled Webpack instead of the default [Turbopack](/docs/app/api-reference/turbopack) bundler for development. |
| `--custom-webpack` | Use [project-installed webpack](/docs/app/guides/custom-webpack) for development. |
| `-p` or `--port <port>` | Specify a port number on which to start the application. Default: 3000, env: PORT | | `-p` or `--port <port>` | Specify a port number on which to start the application. Default: 3000, env: PORT |
| `-H` or `--hostname <hostname>` | Specify a hostname on which to start the application. Useful for making the application available for other devices on the network. Default: 0.0.0.0 | | `-H` or `--hostname <hostname>` | Specify a hostname on which to start the application. Useful for making the application available for other devices on the network. Default: 0.0.0.0 |
| `--experimental-https` | Starts the server with HTTPS and generates a self-signed certificate. | | `--experimental-https` | Starts the server with HTTPS and generates a self-signed certificate. |
...@@ -99,6 +100,7 @@ The following options are available for the `next build` command: ...@@ -99,6 +100,7 @@ The following options are available for the `next build` command:
| `[directory]` | A directory on which to build the application. If not provided, the current directory will be used. | | `[directory]` | A directory on which to build the application. If not provided, the current directory will be used. |
| `--turbopack` | Force enable [Turbopack](/docs/app/api-reference/turbopack) (enabled by default). Also available as `--turbo`. | | `--turbopack` | Force enable [Turbopack](/docs/app/api-reference/turbopack) (enabled by default). Also available as `--turbo`. |
| `--webpack` | Build using the bundled Webpack. | | `--webpack` | Build using the bundled Webpack. |
| `--custom-webpack` | Build using [project-installed webpack](/docs/app/guides/custom-webpack). |
| `--analyze` | Generate bundle analysis data for the interactive analyzer during a Turbopack build. | | `--analyze` | Generate bundle analysis data for the interactive analyzer during a Turbopack build. |
| `-d` or `--debug` | Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown. | | `-d` or `--debug` | Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown. |
| `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). | | `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). |
......
---
title: How to use a custom webpack version in Next.js
nav_title: Custom Webpack
description: Use your application's webpack installation with Next.js instead of the bundled version.
source: app/guides/custom-webpack
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
import '../server/require-hook' import '../server/require-hook'
import os from 'os' import os from 'os'
import path from 'path'
import { import {
Argument, Argument,
Command, Command,
...@@ -207,7 +208,8 @@ program ...@@ -207,7 +208,8 @@ program
.option('--experimental-app-only', 'Builds only App Router routes.') .option('--experimental-app-only', 'Builds only App Router routes.')
.option('--turbo', 'Builds using Turbopack.') .option('--turbo', 'Builds using Turbopack.')
.option('--turbopack', 'Builds using Turbopack.') .option('--turbopack', 'Builds using Turbopack.')
.option('--webpack', 'Builds using webpack.') .option('--webpack', 'Builds using the bundled webpack.')
.option('--custom-webpack', 'Builds using your project-installed webpack.')
.addOption( .addOption(
new Option( new Option(
'--experimental-build-mode [mode]', '--experimental-build-mode [mode]',
...@@ -252,6 +254,9 @@ program ...@@ -252,6 +254,9 @@ program
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
if (options.customWebpack || process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
process.env.NEXT_PRIVATE_LOCAL_WEBPACK = path.resolve(directory || '.')
}
if (options.experimentalCpuProf) { if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1' process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'build-main' process.env.__NEXT_PRIVATE_CPU_PROFILE = 'build-main'
...@@ -401,7 +406,11 @@ program ...@@ -401,7 +406,11 @@ program
) )
.option('--turbo', 'Starts development mode using Turbopack.') .option('--turbo', 'Starts development mode using Turbopack.')
.option('--turbopack', 'Starts development mode using Turbopack.') .option('--turbopack', 'Starts development mode using Turbopack.')
.option('--webpack', 'Starts development mode using webpack.') .option('--webpack', 'Starts development mode using the bundled webpack.')
.option(
'--custom-webpack',
'Starts development mode using your project-installed webpack.'
)
.addOption( .addOption(
new Option( new Option(
'-p, --port <port>', '-p, --port <port>',
...@@ -466,6 +475,11 @@ program ...@@ -466,6 +475,11 @@ program
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
if (options.customWebpack || process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
process.env.NEXT_PRIVATE_LOCAL_WEBPACK = path.resolve(
process.env.NEXT_PRIVATE_DEV_DIR || directory || '.'
)
}
if (options.experimentalCpuProf) { if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1' process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'dev-main' process.env.__NEXT_PRIVATE_CPU_PROFILE = 'dev-main'
......
...@@ -13,8 +13,19 @@ export class OptionalPeerDependencyResolverPlugin { ...@@ -13,8 +13,19 @@ export class OptionalPeerDependencyResolverPlugin {
return callback() return callback()
} }
// popping the stack to prevent the recursion check // Pop the stack to prevent the recursion check. Webpack's bundled
resolveContext.stack?.delete(Array.from(resolveContext.stack).pop()!) // resolver exposes a Set while external resolver versions can expose
// a stack with a pop method.
if (resolveContext.stack) {
const stack = resolveContext.stack as typeof resolveContext.stack & {
pop?: () => unknown
}
if (typeof stack.delete === 'function') {
stack.delete(Array.from(stack).pop()!)
} else {
stack.pop?.()
}
}
resolver.doResolve( resolver.doResolve(
target, target,
......
...@@ -8,29 +8,36 @@ if (process.env.NEXT_RSPACK) { ...@@ -8,29 +8,36 @@ if (process.env.NEXT_RSPACK) {
StringXor: require('./bundle5')().StringXor, StringXor: require('./bundle5')().StringXor,
}) })
} else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) { } else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
const path = require('path')
const projectDir = process.env.NEXT_PRIVATE_LOCAL_WEBPACK
// A bare require here resolves from Next.js's compiled package, which can find
// a different webpack than next.config.js (or none in an isolated install).
// Use the project's resolution base for all webpack imports instead.
const projectRequire = require('module').createRequire(
path.join(
path.isAbsolute(projectDir) ? projectDir : process.cwd(),
'package.json'
)
)
Object.assign(exports, { Object.assign(exports, {
// eslint-disable-next-line import/no-extraneous-dependencies BasicEvaluatedExpression: projectRequire(
BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'), 'webpack/lib/javascript/BasicEvaluatedExpression'
// eslint-disable-next-line import/no-extraneous-dependencies ),
ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'), ConcatenatedModule: projectRequire(
// eslint-disable-next-line import/no-extraneous-dependencies 'webpack/lib/optimize/ConcatenatedModule'
makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute, ),
// eslint-disable-next-line import/no-extraneous-dependencies makePathsAbsolute: projectRequire('webpack/lib/util/identifier')
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'), .makePathsAbsolute,
// eslint-disable-next-line import/no-extraneous-dependencies ModuleFilenameHelpers: projectRequire('webpack/lib/ModuleFilenameHelpers'),
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'), NodeTargetPlugin: projectRequire('webpack/lib/node/NodeTargetPlugin'),
// eslint-disable-next-line import/no-extraneous-dependencies RuntimeGlobals: projectRequire('webpack/lib/RuntimeGlobals'),
RuntimeGlobals: require('webpack/lib/RuntimeGlobals'), SourceMapDevToolModuleOptionsPlugin: projectRequire(
// eslint-disable-next-line import/no-extraneous-dependencies 'webpack/lib/SourceMapDevToolModuleOptionsPlugin'
SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'), ),
// eslint-disable-next-line import/no-extraneous-dependencies StringXor: projectRequire('webpack/lib/util/StringXor'),
StringXor: require('webpack/lib/util/StringXor'), NormalModule: projectRequire('webpack/lib/NormalModule'),
// eslint-disable-next-line import/no-extraneous-dependencies sources: projectRequire('webpack').sources,
NormalModule: require('webpack/lib/NormalModule'), webpack: projectRequire('webpack'),
// eslint-disable-next-line import/no-extraneous-dependencies
sources: require('webpack').sources,
// eslint-disable-next-line import/no-extraneous-dependencies
webpack: require('webpack'),
}) })
} else { } else {
Object.assign(exports, require('./bundle5')()) Object.assign(exports, require('./bundle5')())
......
...@@ -42,6 +42,7 @@ export type NextBuildOptions = { ...@@ -42,6 +42,7 @@ export type NextBuildOptions = {
turbo?: boolean turbo?: boolean
turbopack?: boolean turbopack?: boolean
webpack?: boolean webpack?: boolean
customWebpack?: boolean
experimentalDebugMemoryUsage: boolean experimentalDebugMemoryUsage: boolean
experimentalAppOnly?: boolean experimentalAppOnly?: boolean
experimentalTurbo?: boolean experimentalTurbo?: boolean
......
...@@ -62,6 +62,7 @@ export type NextDevOptions = { ...@@ -62,6 +62,7 @@ export type NextDevOptions = {
turbo?: boolean turbo?: boolean
turbopack?: boolean turbopack?: boolean
webpack?: boolean webpack?: boolean
customWebpack?: boolean
port: number port: number
hostname?: string hostname?: string
experimentalHttps?: boolean experimentalHttps?: boolean
......
...@@ -8,29 +8,36 @@ if (process.env.NEXT_RSPACK) { ...@@ -8,29 +8,36 @@ if (process.env.NEXT_RSPACK) {
StringXor: require('./bundle5')().StringXor, StringXor: require('./bundle5')().StringXor,
}) })
} else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) { } else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
const path = require('path')
const projectDir = process.env.NEXT_PRIVATE_LOCAL_WEBPACK
// A bare require here resolves from Next.js's compiled package, which can find
// a different webpack than next.config.js (or none in an isolated install).
// Use the project's resolution base for all webpack imports instead.
const projectRequire = require('module').createRequire(
path.join(
path.isAbsolute(projectDir) ? projectDir : process.cwd(),
'package.json'
)
)
Object.assign(exports, { Object.assign(exports, {
// eslint-disable-next-line import/no-extraneous-dependencies BasicEvaluatedExpression: projectRequire(
BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'), 'webpack/lib/javascript/BasicEvaluatedExpression'
// eslint-disable-next-line import/no-extraneous-dependencies ),
ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'), ConcatenatedModule: projectRequire(
// eslint-disable-next-line import/no-extraneous-dependencies 'webpack/lib/optimize/ConcatenatedModule'
makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute, ),
// eslint-disable-next-line import/no-extraneous-dependencies makePathsAbsolute: projectRequire('webpack/lib/util/identifier')
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'), .makePathsAbsolute,
// eslint-disable-next-line import/no-extraneous-dependencies ModuleFilenameHelpers: projectRequire('webpack/lib/ModuleFilenameHelpers'),
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'), NodeTargetPlugin: projectRequire('webpack/lib/node/NodeTargetPlugin'),
// eslint-disable-next-line import/no-extraneous-dependencies RuntimeGlobals: projectRequire('webpack/lib/RuntimeGlobals'),
RuntimeGlobals: require('webpack/lib/RuntimeGlobals'), SourceMapDevToolModuleOptionsPlugin: projectRequire(
// eslint-disable-next-line import/no-extraneous-dependencies 'webpack/lib/SourceMapDevToolModuleOptionsPlugin'
SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'), ),
// eslint-disable-next-line import/no-extraneous-dependencies StringXor: projectRequire('webpack/lib/util/StringXor'),
StringXor: require('webpack/lib/util/StringXor'), NormalModule: projectRequire('webpack/lib/NormalModule'),
// eslint-disable-next-line import/no-extraneous-dependencies sources: projectRequire('webpack').sources,
NormalModule: require('webpack/lib/NormalModule'), webpack: projectRequire('webpack'),
// eslint-disable-next-line import/no-extraneous-dependencies
sources: require('webpack').sources,
// eslint-disable-next-line import/no-extraneous-dependencies
webpack: require('webpack'),
}) })
} else { } else {
Object.assign(exports, require('./bundle5')()) Object.assign(exports, require('./bundle5')())
......
...@@ -42,6 +42,7 @@ export function parseBundlerArgs(options: { ...@@ -42,6 +42,7 @@ export function parseBundlerArgs(options: {
turbo?: boolean turbo?: boolean
turbopack?: boolean turbopack?: boolean
webpack?: boolean webpack?: boolean
customWebpack?: boolean
}): Bundler { }): Bundler {
const bundlerFlags = new Map<Bundler, string[]>() const bundlerFlags = new Map<Bundler, string[]>()
const setBundlerFlag = (bundler: Bundler, flag: string) => { const setBundlerFlag = (bundler: Bundler, flag: string) => {
...@@ -68,6 +69,9 @@ export function parseBundlerArgs(options: { ...@@ -68,6 +69,9 @@ export function parseBundlerArgs(options: {
if (options.webpack) { if (options.webpack) {
setBundlerFlag(Bundler.Webpack, '--webpack') setBundlerFlag(Bundler.Webpack, '--webpack')
} }
if (options.customWebpack) {
setBundlerFlag(Bundler.Webpack, '--custom-webpack')
}
if (process.env.IS_WEBPACK_TEST) { if (process.env.IS_WEBPACK_TEST) {
setBundlerFlag( setBundlerFlag(
...@@ -88,7 +92,10 @@ export function parseBundlerArgs(options: { ...@@ -88,7 +92,10 @@ export function parseBundlerArgs(options: {
) )
} }
if (bundlerFlags.size > 1) { if (
bundlerFlags.size > 1 ||
(options.webpack === true && options.customWebpack === true)
) {
console.error( console.error(
`Multiple bundler flags set: ${Array.from(bundlerFlags.values()).flat().join(', ')}. `Multiple bundler flags set: ${Array.from(bundlerFlags.values()).flat().join(', ')}.
......
let installed: boolean = false let installed: boolean = false
export function loadWebpackHook() { export function loadWebpackHook(webpackProjectDir: string) {
if (installed) { if (installed) {
return return
} }
installed = true installed = true
// hook the Node.js require so that webpack requires are const requireHook =
// routed to the bundled and now initialized webpack version
;(
require('../server/require-hook') as typeof import('../server/require-hook') require('../server/require-hook') as typeof import('../server/require-hook')
).addHookAliases( const customWebpack = Boolean(process.env.NEXT_PRIVATE_LOCAL_WEBPACK)
[ if (customWebpack) {
try {
require.resolve('webpack/package.json', { paths: [webpackProjectDir] })
} catch (cause) {
installed = false
throw new Error(
'`--custom-webpack` requires webpack to be installed in your project. Install it with `npm install --save-dev webpack`.',
{ cause }
)
}
}
const webpackAliases: [string, string][] = [
['webpack', 'next/dist/compiled/webpack/webpack-lib'], ['webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/package', 'next/dist/compiled/webpack/package'], ['webpack/package', 'next/dist/compiled/webpack/package'],
['webpack/package.json', 'next/dist/compiled/webpack/package'], ['webpack/package.json', 'next/dist/compiled/webpack/package'],
...@@ -122,22 +132,27 @@ export function loadWebpackHook() { ...@@ -122,22 +132,27 @@ export function loadWebpackHook() {
'next/dist/compiled/webpack/ModuleFilenameHelpers', 'next/dist/compiled/webpack/ModuleFilenameHelpers',
], ],
['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'], ['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'],
[ ['webpack/lib/GraphHelpers.js', 'next/dist/compiled/webpack/GraphHelpers'],
'webpack/lib/GraphHelpers.js',
'next/dist/compiled/webpack/GraphHelpers',
],
['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'], ['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'],
['webpack-sources', 'next/dist/compiled/webpack/sources'], ['webpack-sources', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib', 'next/dist/compiled/webpack/sources'], ['webpack-sources/lib', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'], ['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'], ['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'],
]
// Only bundled webpack needs require aliases. With `--custom-webpack`,
// webpack and webpack-sources resolve normally from the project.
requireHook.addHookAliases(
[
...(customWebpack ? [] : webpackAliases),
['@babel/runtime', 'next/dist/compiled/@babel/runtime/package.json'], ['@babel/runtime', 'next/dist/compiled/@babel/runtime/package.json'],
[ [
'@babel/runtime/package.json', '@babel/runtime/package.json',
'next/dist/compiled/@babel/runtime/package.json', 'next/dist/compiled/@babel/runtime/package.json',
], ],
].map( ].map(
// Use dynamic require.resolve to avoid statically analyzable since they're only for build time // Use dynamic require.resolve to avoid statically analyzable since
// these replacements are only needed at build time.
([request, replacement]) => [request, require.resolve(replacement)] ([request, replacement]) => [request, require.resolve(replacement)]
) )
) )
......
...@@ -2025,7 +2025,7 @@ async function loadConfigImpl( ...@@ -2025,7 +2025,7 @@ async function loadConfigImpl(
// Original implementation continues below... // Original implementation continues below...
if (!process.env.__NEXT_PRIVATE_RENDER_WORKER) { if (!process.env.__NEXT_PRIVATE_RENDER_WORKER) {
try { try {
loadWebpackHook() loadWebpackHook(dir)
} catch (err) { } catch (err) {
// this can fail in standalone mode as the files // this can fail in standalone mode as the files
// aren't traced/included // aren't traced/included
......
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const message = 'original module'
import { message } from './message'
export default function Page() {
return (
<main>
<p id="webpack-version">{process.env.CUSTOM_WEBPACK_PLUGIN_VALUE}</p>
<p id="replacement-message">{message}</p>
</main>
)
}
export const message = 'replaced by NormalModuleReplacementPlugin'
class CustomWebpackPlugin {
constructor(webpackVersion) {
this.webpackVersion = webpackVersion
}
apply(compiler) {
new compiler.webpack.DefinePlugin({
'process.env.CUSTOM_WEBPACK_PLUGIN_VALUE': JSON.stringify(
`custom plugin with webpack ${this.webpackVersion}`
),
}).apply(compiler)
}
}
module.exports = { CustomWebpackPlugin }
import type { ChildProcess } from 'child_process'
import { promises as fs } from 'fs'
import { createRequire } from 'module'
import path from 'path'
import { isNextDeploy, isNextDev, nextTestSetup } from 'e2e-utils'
import { findPort, killApp, retry } from 'next-test-utils'
const webpackVersions = ['5.98.0', '5.111.0']
for (const webpackVersion of webpackVersions) {
// @force-gate webpack
describe(`--custom-webpack with webpack ${webpackVersion}`, () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
webpack: webpackVersion,
},
env: {
EXPECTED_WEBPACK_VERSION: webpackVersion,
},
buildCommand: 'pnpm next build --custom-webpack',
startCommand: isNextDev
? 'pnpm next dev --custom-webpack'
: 'pnpm next start',
})
it('uses project webpack during config evaluation and compilation', async () => {
const $ = await next.render$('/')
expect($('#webpack-version').text()).toBe(
`custom plugin with webpack ${webpackVersion}`
)
expect($('#replacement-message').text()).toBe(
'replaced by NormalModuleReplacementPlugin'
)
})
})
}
// @force-gate webpack
describe('--custom-webpack with a shadowed webpack and no pnpm hoisting', () => {
const webpackVersion = '5.111.0'
const { next } = nextTestSetup({
files: __dirname,
overrideFiles: {
'pnpm-workspace.yaml': 'hoistPattern: []\n',
},
dependencies: {
webpack: webpackVersion,
'webpack-old': 'npm:webpack@5.98.0',
},
env: {
EXPECTED_WEBPACK_VERSION: webpackVersion,
},
buildCommand: 'pnpm next build --custom-webpack',
startCommand: isNextDev
? 'pnpm next dev --custom-webpack'
: 'pnpm next start',
skipStart: true,
})
it('uses the project webpack, not the one next would resolve', async () => {
if (isNextDeploy) {
// Deployed builds cannot shadow the installed Next.js package locally.
// Still verify the deployed build uses the application's webpack.
await next.start()
const $ = await next.render$('/')
expect($('#webpack-version').text()).toBe(
`custom plugin with webpack ${webpackVersion}`
)
return
}
if (process.env.NEXT_SKIP_ISOLATE) {
// The non-isolated Next.js package is the checkout itself, so shadowing
// its node_modules would modify the developer's workspace. Check the
// project-scoped loader using the workspace webpack instead.
const result = await next.runCommand(['build', '--custom-webpack'], {
env: { EXPECTED_WEBPACK_VERSION: '5.98.0' },
})
expect(result.exitCode).toBe(0)
return
}
const nextPackageDir = path.dirname(
require.resolve('next/package.json', { paths: [next.testDir] })
)
const shadowPath = path.join(nextPackageDir, 'node_modules', 'webpack')
await fs.mkdir(path.dirname(shadowPath), { recursive: true })
await fs.symlink(
await fs.realpath(path.join(next.testDir, 'node_modules', 'webpack-old')),
shadowPath,
'junction'
)
const wrapperRequire = createRequire(
path.join(nextPackageDir, 'dist/compiled/webpack/webpack.js')
)
const projectRequire = createRequire(
path.join(next.testDir, 'package.json')
)
expect(projectRequire('webpack/package.json').version).toBe(webpackVersion)
expect(wrapperRequire('webpack/package.json').version).toBe('5.98.0')
await next.start()
const $ = await next.render$('/')
expect($('#webpack-version').text()).toBe(
`custom plugin with webpack ${webpackVersion}`
)
expect($('#replacement-message').text()).toBe(
'replaced by NormalModuleReplacementPlugin'
)
})
})
// @force-gate webpack
describe('--custom-webpack with an explicit application directory', () => {
const webpackVersion = '5.111.0'
const { next } = nextTestSetup({
files: __dirname,
dependencies: { webpack: webpackVersion },
env: { EXPECTED_WEBPACK_VERSION: webpackVersion },
buildCommand: 'pnpm next build --custom-webpack',
startCommand: isNextDev
? 'pnpm next dev --custom-webpack'
: 'pnpm next start',
skipStart: true,
})
it('resolves webpack from the application, not the working directory', async () => {
if (isNextDeploy) {
// There is no local CLI process or working directory in a deployment.
// Verify the deployed build still uses the application's webpack.
await next.start()
const $ = await next.render$('/')
expect($('#webpack-version').text()).toBe(
`custom plugin with webpack ${webpackVersion}`
)
return
}
const cwd = path.dirname(next.testDir)
const expectedVersion = process.env.NEXT_SKIP_ISOLATE
? '5.98.0'
: webpackVersion
const env = { EXPECTED_WEBPACK_VERSION: expectedVersion }
if (isNextDev) {
const port = await findPort()
let child: ChildProcess | undefined
const running = next.runCommand(
['dev', next.testDir, '--custom-webpack', '-p', String(port)],
{
cwd,
env,
instance(childProcess) {
child = childProcess
},
}
)
try {
await Promise.race([
retry(async () => {
const response = await fetch(`http://localhost:${port}/`)
expect(response.status).toBe(200)
const html = await response.text()
expect(html).toContain(
`custom plugin with webpack ${expectedVersion}`
)
expect(html).toContain('replaced by NormalModuleReplacementPlugin')
}, 30_000),
running.then((result) => {
throw new Error(`next dev exited early:\n${result.cliOutput}`)
}),
])
} finally {
if (child) {
await killApp(child).catch(() => {})
}
await running.catch(() => {})
}
} else {
const result = await next.runCommand(
['build', next.testDir, '--custom-webpack'],
{ cwd, env }
)
if (result.exitCode !== 0) {
throw new Error(`next build failed:\n${result.cliOutput}`)
}
expect(result.cliOutput).toContain('Compiled successfully')
}
}, 240_000)
})
// @force-gate webpack
describe('--custom-webpack without a webpack dependency', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {},
buildCommand: 'pnpm next build --custom-webpack',
startCommand: isNextDev
? 'pnpm next dev --custom-webpack'
: 'pnpm next start',
skipStart: true,
})
it('reports how to install webpack', async () => {
await next.start().catch(() => {})
await retry(() => {
expect(next.cliOutput).toContain(
'`--custom-webpack` requires webpack to be installed in your project'
)
})
})
})
// @force-gate webpack
describe('--webpack without a webpack dependency', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {},
buildCommand: 'pnpm next build --webpack',
startCommand: isNextDev ? 'pnpm next dev --webpack' : 'pnpm next start',
})
it('uses bundled webpack without requiring a project webpack installation', async () => {
const html = await next.render('/')
expect(html).toContain('original module')
})
})
for (const conflictingFlag of ['--webpack', '--turbopack']) {
// @force-gate webpack
describe(`--custom-webpack with ${conflictingFlag}`, () => {
const command = `pnpm next ${isNextDev ? 'dev' : 'build'} --custom-webpack ${conflictingFlag}`
const { next } = nextTestSetup({
files: __dirname,
dependencies: {},
buildCommand: command,
startCommand: command,
skipStart: true,
})
it('reports conflicting bundler flags', async () => {
await next.start().catch(() => {})
await retry(() => {
expect(next.cliOutput).toContain('Multiple bundler flags set:')
expect(next.cliOutput).toContain('--custom-webpack')
expect(next.cliOutput).toContain(conflictingFlag)
})
})
})
}
const path = require('path')
const webpack = require('webpack')
const webpackPackageVersion = require('webpack/package.json').version
const extensionlessWebpackPackageVersion = require('webpack/package').version
if (extensionlessWebpackPackageVersion !== webpackPackageVersion) {
throw new Error(
'Webpack package metadata requests returned different versions'
)
}
const { CustomWebpackPlugin } = require('./custom-webpack-plugin')
if (
process.env.NEXT_PRIVATE_LOCAL_WEBPACK &&
process.env.EXPECTED_WEBPACK_VERSION &&
webpackPackageVersion !== process.env.EXPECTED_WEBPACK_VERSION
) {
throw new Error(
`Expected config webpack ${process.env.EXPECTED_WEBPACK_VERSION}, received ${webpackPackageVersion}`
)
}
/** @type {import('next').NextConfig} */
module.exports = {
webpack(config, { webpack: callbackWebpack }) {
if (
process.env.EXPECTED_WEBPACK_VERSION &&
callbackWebpack.version !== process.env.EXPECTED_WEBPACK_VERSION
) {
throw new Error(
`Expected callback webpack ${process.env.EXPECTED_WEBPACK_VERSION}, received ${callbackWebpack.version}`
)
}
if (callbackWebpack !== webpack) {
throw new Error(
'Webpack callback and config require returned different instances'
)
}
if (process.env.EXPECTED_WEBPACK_VERSION) {
config.plugins.push(
new CustomWebpackPlugin(webpackPackageVersion),
new webpack.NormalModuleReplacementPlugin(
/^\.\/message$/,
path.resolve(__dirname, 'app/replacement-message.js')
)
)
}
return 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