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

Add experimental custom webpack support (#98862)

### What?

Add the experimental `customWebpack` configuration option so
webpack-mode applications can use a project-installed webpack version
instead of the version bundled with Next.js. Webpack is now an optional
`^5.98.0` peer dependency, and the new option is documented with
end-to-end coverage for webpack 5.98.0 and 5.111.0.

### Why?

Next.js currently redirects webpack imports to its bundled
implementation. This prevents applications from opting into newer
compatible webpack releases or validating upgrades independently. The
new option provides an explicit escape hatch while preserving the
bundled implementation as the default.

### How?

After configuration is resolved, webpack-mode startup redirects the
existing webpack require-hook aliases to the package resolved from the
application. The selection is propagated to webpack build workers
through the existing local-webpack runtime switch. If the optional peer
cannot be resolved, Next.js restores its bundled aliases and reports an
actionable installation error.

The implementation only activates for webpack, leaving Turbopack and
Rspack unchanged. It also handles the resolver stack API exposed by
external webpack versions. The test matrix verifies the selected
compiler version, rendering in development and production, the
build-worker path, missing-peer diagnostics, and bundled fallback
behavior when the option is disabled.

### Verification

- `pnpm test-dev-webpack
test/e2e/app-dir/custom-webpack/custom-webpack.test.ts`
- `pnpm test-start-webpack
test/e2e/app-dir/custom-webpack/custom-webpack.test.ts`
- `pnpm --filter=next types`

<!-- 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 ccbd0cb5
...@@ -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 the project-installed `webpack` peer dependency (`^5.98.0`) 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. |
...@@ -98,7 +99,8 @@ The following options are available for the `next build` command: ...@@ -98,7 +99,8 @@ The following options are available for the `next build` command:
| `-h, --help` | Show all available options. | | `-h, --help` | Show all available options. |
| `[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 Webpack. | | `--webpack` | Build using the bundled Webpack. |
| `--custom-webpack` | Build using the project-installed `webpack` peer dependency (`^5.98.0`). |
| `-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). |
| `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. | | `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. |
......
...@@ -113,7 +113,8 @@ ...@@ -113,7 +113,8 @@
"babel-plugin-react-compiler": "*", "babel-plugin-react-compiler": "*",
"react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",
"react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",
"sass": "^1.3.0" "sass": "^1.3.0",
"webpack": "^5.98.0"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"babel-plugin-react-compiler": { "babel-plugin-react-compiler": {
...@@ -122,6 +123,9 @@ ...@@ -122,6 +123,9 @@
"sass": { "sass": {
"optional": true "optional": true
}, },
"webpack": {
"optional": true
},
"@opentelemetry/api": { "@opentelemetry/api": {
"optional": true "optional": true
}, },
......
...@@ -208,7 +208,8 @@ program ...@@ -208,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]',
...@@ -253,6 +254,9 @@ program ...@@ -253,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 = '1'
}
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'
...@@ -342,7 +346,11 @@ program ...@@ -342,7 +346,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>',
...@@ -407,6 +415,9 @@ program ...@@ -407,6 +415,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 = '1'
}
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,
......
/* eslint-disable import/no-extraneous-dependencies */
module.exports = function () { module.exports = function () {
return { return {
BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'), BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'),
......
...@@ -9,27 +9,16 @@ if (process.env.NEXT_RSPACK) { ...@@ -9,27 +9,16 @@ if (process.env.NEXT_RSPACK) {
}) })
} else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) { } else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
Object.assign(exports, { Object.assign(exports, {
// eslint-disable-next-line import/no-extraneous-dependencies
BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'), BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'),
// eslint-disable-next-line import/no-extraneous-dependencies
ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'), ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'),
// eslint-disable-next-line import/no-extraneous-dependencies
makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute, makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute,
// eslint-disable-next-line import/no-extraneous-dependencies
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'), ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'),
// eslint-disable-next-line import/no-extraneous-dependencies
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'), NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'),
// eslint-disable-next-line import/no-extraneous-dependencies
RuntimeGlobals: require('webpack/lib/RuntimeGlobals'), RuntimeGlobals: require('webpack/lib/RuntimeGlobals'),
// eslint-disable-next-line import/no-extraneous-dependencies
SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'), SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'),
// eslint-disable-next-line import/no-extraneous-dependencies
StringXor: require('webpack/lib/util/StringXor'), StringXor: require('webpack/lib/util/StringXor'),
// eslint-disable-next-line import/no-extraneous-dependencies
NormalModule: require('webpack/lib/NormalModule'), NormalModule: require('webpack/lib/NormalModule'),
// eslint-disable-next-line import/no-extraneous-dependencies
sources: require('webpack').sources, sources: require('webpack').sources,
// eslint-disable-next-line import/no-extraneous-dependencies
webpack: require('webpack'), webpack: require('webpack'),
}) })
} else { } else {
......
...@@ -22,6 +22,7 @@ export type NextBuildOptions = { ...@@ -22,6 +22,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
......
...@@ -51,6 +51,7 @@ export type NextDevOptions = { ...@@ -51,6 +51,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
......
...@@ -9,27 +9,16 @@ if (process.env.NEXT_RSPACK) { ...@@ -9,27 +9,16 @@ if (process.env.NEXT_RSPACK) {
}) })
} else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) { } else if (process.env.NEXT_PRIVATE_LOCAL_WEBPACK) {
Object.assign(exports, { Object.assign(exports, {
// eslint-disable-next-line import/no-extraneous-dependencies
BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'), BasicEvaluatedExpression: require('webpack/lib/javascript/BasicEvaluatedExpression'),
// eslint-disable-next-line import/no-extraneous-dependencies
ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'), ConcatenatedModule: require('webpack/lib/optimize/ConcatenatedModule'),
// eslint-disable-next-line import/no-extraneous-dependencies
makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute, makePathsAbsolute: require('webpack/lib/util/identifier').makePathsAbsolute,
// eslint-disable-next-line import/no-extraneous-dependencies
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'), ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'),
// eslint-disable-next-line import/no-extraneous-dependencies
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'), NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'),
// eslint-disable-next-line import/no-extraneous-dependencies
RuntimeGlobals: require('webpack/lib/RuntimeGlobals'), RuntimeGlobals: require('webpack/lib/RuntimeGlobals'),
// eslint-disable-next-line import/no-extraneous-dependencies
SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'), SourceMapDevToolModuleOptionsPlugin: require('webpack/lib/SourceMapDevToolModuleOptionsPlugin'),
// eslint-disable-next-line import/no-extraneous-dependencies
StringXor: require('webpack/lib/util/StringXor'), StringXor: require('webpack/lib/util/StringXor'),
// eslint-disable-next-line import/no-extraneous-dependencies
NormalModule: require('webpack/lib/NormalModule'), NormalModule: require('webpack/lib/NormalModule'),
// eslint-disable-next-line import/no-extraneous-dependencies
sources: require('webpack').sources, sources: require('webpack').sources,
// eslint-disable-next-line import/no-extraneous-dependencies
webpack: require('webpack'), webpack: require('webpack'),
}) })
} else { } else {
......
...@@ -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/package.json', 'next/dist/compiled/webpack/package'],
['webpack/lib/webpack', 'next/dist/compiled/webpack/webpack-lib'],
['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'],
[ [
['webpack', 'next/dist/compiled/webpack/webpack-lib'], 'webpack/lib/node/NodeEnvironmentPlugin',
['webpack/package', 'next/dist/compiled/webpack/package'], 'next/dist/compiled/webpack/NodeEnvironmentPlugin',
['webpack/package.json', 'next/dist/compiled/webpack/package'], ],
['webpack/lib/webpack', 'next/dist/compiled/webpack/webpack-lib'], [
['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'], 'webpack/lib/node/NodeEnvironmentPlugin.js',
[ 'next/dist/compiled/webpack/NodeEnvironmentPlugin',
'webpack/lib/node/NodeEnvironmentPlugin', ],
'next/dist/compiled/webpack/NodeEnvironmentPlugin', [
], 'webpack/lib/BasicEvaluatedExpression',
[ 'next/dist/compiled/webpack/BasicEvaluatedExpression',
'webpack/lib/node/NodeEnvironmentPlugin.js', ],
'next/dist/compiled/webpack/NodeEnvironmentPlugin', [
], 'webpack/lib/BasicEvaluatedExpression.js',
[ 'next/dist/compiled/webpack/BasicEvaluatedExpression',
'webpack/lib/BasicEvaluatedExpression', ],
'next/dist/compiled/webpack/BasicEvaluatedExpression', [
], 'webpack/lib/node/NodeTargetPlugin',
[ 'next/dist/compiled/webpack/NodeTargetPlugin',
'webpack/lib/BasicEvaluatedExpression.js', ],
'next/dist/compiled/webpack/BasicEvaluatedExpression', [
], 'webpack/lib/node/NodeTargetPlugin.js',
[ 'next/dist/compiled/webpack/NodeTargetPlugin',
'webpack/lib/node/NodeTargetPlugin', ],
'next/dist/compiled/webpack/NodeTargetPlugin', [
], 'webpack/lib/node/NodeTemplatePlugin',
[ 'next/dist/compiled/webpack/NodeTemplatePlugin',
'webpack/lib/node/NodeTargetPlugin.js', ],
'next/dist/compiled/webpack/NodeTargetPlugin', [
], 'webpack/lib/node/NodeTemplatePlugin.js',
[ 'next/dist/compiled/webpack/NodeTemplatePlugin',
'webpack/lib/node/NodeTemplatePlugin', ],
'next/dist/compiled/webpack/NodeTemplatePlugin', [
], 'webpack/lib/LibraryTemplatePlugin',
[ 'next/dist/compiled/webpack/LibraryTemplatePlugin',
'webpack/lib/node/NodeTemplatePlugin.js', ],
'next/dist/compiled/webpack/NodeTemplatePlugin', [
], 'webpack/lib/LibraryTemplatePlugin.js',
[ 'next/dist/compiled/webpack/LibraryTemplatePlugin',
'webpack/lib/LibraryTemplatePlugin', ],
'next/dist/compiled/webpack/LibraryTemplatePlugin', [
], 'webpack/lib/SingleEntryPlugin',
[ 'next/dist/compiled/webpack/SingleEntryPlugin',
'webpack/lib/LibraryTemplatePlugin.js', ],
'next/dist/compiled/webpack/LibraryTemplatePlugin', [
], 'webpack/lib/SingleEntryPlugin.js',
[ 'next/dist/compiled/webpack/SingleEntryPlugin',
'webpack/lib/SingleEntryPlugin', ],
'next/dist/compiled/webpack/SingleEntryPlugin', [
], 'webpack/lib/optimize/LimitChunkCountPlugin',
[ 'next/dist/compiled/webpack/LimitChunkCountPlugin',
'webpack/lib/SingleEntryPlugin.js', ],
'next/dist/compiled/webpack/SingleEntryPlugin', [
], 'webpack/lib/optimize/LimitChunkCountPlugin.js',
[ 'next/dist/compiled/webpack/LimitChunkCountPlugin',
'webpack/lib/optimize/LimitChunkCountPlugin', ],
'next/dist/compiled/webpack/LimitChunkCountPlugin', [
], 'webpack/lib/webworker/WebWorkerTemplatePlugin',
[ 'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
'webpack/lib/optimize/LimitChunkCountPlugin.js', ],
'next/dist/compiled/webpack/LimitChunkCountPlugin', [
], 'webpack/lib/webworker/WebWorkerTemplatePlugin.js',
[ 'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
'webpack/lib/webworker/WebWorkerTemplatePlugin', ],
'next/dist/compiled/webpack/WebWorkerTemplatePlugin', [
], 'webpack/lib/ExternalsPlugin',
[ 'next/dist/compiled/webpack/ExternalsPlugin',
'webpack/lib/webworker/WebWorkerTemplatePlugin.js', ],
'next/dist/compiled/webpack/WebWorkerTemplatePlugin', [
], 'webpack/lib/ExternalsPlugin.js',
[ 'next/dist/compiled/webpack/ExternalsPlugin',
'webpack/lib/ExternalsPlugin', ],
'next/dist/compiled/webpack/ExternalsPlugin', [
], 'webpack/lib/web/FetchCompileWasmTemplatePlugin',
[ 'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
'webpack/lib/ExternalsPlugin.js', ],
'next/dist/compiled/webpack/ExternalsPlugin', [
], 'webpack/lib/web/FetchCompileWasmTemplatePlugin.js',
[ 'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
'webpack/lib/web/FetchCompileWasmTemplatePlugin', ],
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin', [
], 'webpack/lib/web/FetchCompileWasmPlugin',
[ 'next/dist/compiled/webpack/FetchCompileWasmPlugin',
'webpack/lib/web/FetchCompileWasmTemplatePlugin.js', ],
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin', [
], 'webpack/lib/web/FetchCompileWasmPlugin.js',
[ 'next/dist/compiled/webpack/FetchCompileWasmPlugin',
'webpack/lib/web/FetchCompileWasmPlugin', ],
'next/dist/compiled/webpack/FetchCompileWasmPlugin', [
], 'webpack/lib/web/FetchCompileAsyncWasmPlugin',
[ 'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
'webpack/lib/web/FetchCompileWasmPlugin.js', ],
'next/dist/compiled/webpack/FetchCompileWasmPlugin', [
], 'webpack/lib/web/FetchCompileAsyncWasmPlugin.js',
[ 'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
'webpack/lib/web/FetchCompileAsyncWasmPlugin', ],
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin', [
], 'webpack/lib/ModuleFilenameHelpers',
[ 'next/dist/compiled/webpack/ModuleFilenameHelpers',
'webpack/lib/web/FetchCompileAsyncWasmPlugin.js', ],
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin', [
], 'webpack/lib/ModuleFilenameHelpers.js',
[ 'next/dist/compiled/webpack/ModuleFilenameHelpers',
'webpack/lib/ModuleFilenameHelpers', ],
'next/dist/compiled/webpack/ModuleFilenameHelpers', ['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'],
], ['webpack/lib/GraphHelpers.js', 'next/dist/compiled/webpack/GraphHelpers'],
[ ['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'],
'webpack/lib/ModuleFilenameHelpers.js', ['webpack-sources', 'next/dist/compiled/webpack/sources'],
'next/dist/compiled/webpack/ModuleFilenameHelpers', ['webpack-sources/lib', 'next/dist/compiled/webpack/sources'],
], ['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'],
['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'], ['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'],
[ ]
'webpack/lib/GraphHelpers.js',
'next/dist/compiled/webpack/GraphHelpers', // Only bundled webpack needs require aliases. With `--custom-webpack`,
], // webpack and webpack-sources resolve normally from the project.
['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'], requireHook.addHookAliases(
['webpack-sources', 'next/dist/compiled/webpack/sources'], [
['webpack-sources/lib', 'next/dist/compiled/webpack/sources'], ...(customWebpack ? [] : webpackAliases),
['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'],
['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'],
['@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)]
) )
) )
......
...@@ -1999,7 +1999,7 @@ async function loadConfigImpl( ...@@ -1999,7 +1999,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 { isNextDev, nextTestSetup } from 'e2e-utils'
import { 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 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 the peer dependency', 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 { 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