Unverified Commit 58ad0793 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Revert "Add experimental custom webpack support" (#99227)

This produces a new dependency chain which can lead to duplicate Next.js
version in monorepo setups.

Specifically, the internal sync is broken. It can probably be fixed with
some dependency graph doctoring but we need to investigate and document
that first. We're close to a stable release and the sync has been
blocked all week so getting it back on track has priority.

Reverts https://github.com/vercel/next.js/pull/98862
parent 3192e47e
...@@ -66,8 +66,7 @@ The following options are available when running `next dev`: ...@@ -66,8 +66,7 @@ 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 the bundled Webpack instead of the default [Turbopack](/docs/app/api-reference/turbopack) bundler for development. | | `--webpack` | Use 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. |
...@@ -100,7 +99,6 @@ The following options are available for the `next build` command: ...@@ -100,7 +99,6 @@ 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 the project-installed `webpack` peer dependency (`^5.98.0`). |
| `--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). |
......
...@@ -113,8 +113,7 @@ ...@@ -113,8 +113,7 @@
"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": {
...@@ -123,9 +122,6 @@ ...@@ -123,9 +122,6 @@
"sass": { "sass": {
"optional": true "optional": true
}, },
"webpack": {
"optional": true
},
"@opentelemetry/api": { "@opentelemetry/api": {
"optional": true "optional": true
}, },
......
...@@ -206,8 +206,7 @@ program ...@@ -206,8 +206,7 @@ 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 the bundled webpack.') .option('--webpack', 'Builds using 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,9 +251,6 @@ program ...@@ -252,9 +251,6 @@ 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'
...@@ -345,11 +341,7 @@ program ...@@ -345,11 +341,7 @@ 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 the bundled webpack.') .option('--webpack', 'Starts development mode using webpack.')
.option(
'--custom-webpack',
'Starts development mode using your project-installed webpack.'
)
.addOption( .addOption(
new Option( new Option(
'-p, --port <port>', '-p, --port <port>',
...@@ -414,9 +406,6 @@ program ...@@ -414,9 +406,6 @@ 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,19 +13,8 @@ export class OptionalPeerDependencyResolverPlugin { ...@@ -13,19 +13,8 @@ export class OptionalPeerDependencyResolverPlugin {
return callback() return callback()
} }
// Pop the stack to prevent the recursion check. Webpack's bundled // popping the stack to prevent the recursion check
// resolver exposes a Set while external resolver versions can expose resolveContext.stack?.delete(Array.from(resolveContext.stack).pop()!)
// 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,16 +9,27 @@ if (process.env.NEXT_RSPACK) { ...@@ -9,16 +9,27 @@ 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 {
......
...@@ -23,7 +23,6 @@ export type NextBuildOptions = { ...@@ -23,7 +23,6 @@ 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,7 +51,6 @@ export type NextDevOptions = { ...@@ -51,7 +51,6 @@ 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,16 +9,27 @@ if (process.env.NEXT_RSPACK) { ...@@ -9,16 +9,27 @@ 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,7 +42,6 @@ export function parseBundlerArgs(options: { ...@@ -42,7 +42,6 @@ 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) => {
...@@ -69,9 +68,6 @@ export function parseBundlerArgs(options: { ...@@ -69,9 +68,6 @@ 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(
...@@ -92,10 +88,7 @@ export function parseBundlerArgs(options: { ...@@ -92,10 +88,7 @@ export function parseBundlerArgs(options: {
) )
} }
if ( if (bundlerFlags.size > 1) {
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(webpackProjectDir: string) { export function loadWebpackHook() {
if (installed) { if (installed) {
return return
} }
installed = true installed = true
const requireHook = // hook the Node.js require so that webpack requires are
// 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')
const customWebpack = Boolean(process.env.NEXT_PRIVATE_LOCAL_WEBPACK) ).addHookAliases(
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/lib/node/NodeEnvironmentPlugin',
'next/dist/compiled/webpack/NodeEnvironmentPlugin',
],
[
'webpack/lib/node/NodeEnvironmentPlugin.js',
'next/dist/compiled/webpack/NodeEnvironmentPlugin',
],
[
'webpack/lib/BasicEvaluatedExpression',
'next/dist/compiled/webpack/BasicEvaluatedExpression',
],
[
'webpack/lib/BasicEvaluatedExpression.js',
'next/dist/compiled/webpack/BasicEvaluatedExpression',
],
[
'webpack/lib/node/NodeTargetPlugin',
'next/dist/compiled/webpack/NodeTargetPlugin',
],
[
'webpack/lib/node/NodeTargetPlugin.js',
'next/dist/compiled/webpack/NodeTargetPlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin.js',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin.js',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/SingleEntryPlugin',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/SingleEntryPlugin.js',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin.js',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin.js',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/ExternalsPlugin',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/ExternalsPlugin.js',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[ [
'webpack/lib/web/FetchCompileWasmTemplatePlugin.js', ['webpack', 'next/dist/compiled/webpack/webpack-lib'],
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin', ['webpack/package', 'next/dist/compiled/webpack/package'],
], ['webpack/package.json', 'next/dist/compiled/webpack/package'],
[ ['webpack/lib/webpack', 'next/dist/compiled/webpack/webpack-lib'],
'webpack/lib/web/FetchCompileWasmPlugin', ['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'],
'next/dist/compiled/webpack/FetchCompileWasmPlugin', [
], 'webpack/lib/node/NodeEnvironmentPlugin',
[ 'next/dist/compiled/webpack/NodeEnvironmentPlugin',
'webpack/lib/web/FetchCompileWasmPlugin.js', ],
'next/dist/compiled/webpack/FetchCompileWasmPlugin', [
], 'webpack/lib/node/NodeEnvironmentPlugin.js',
[ 'next/dist/compiled/webpack/NodeEnvironmentPlugin',
'webpack/lib/web/FetchCompileAsyncWasmPlugin', ],
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin', [
], 'webpack/lib/BasicEvaluatedExpression',
[ 'next/dist/compiled/webpack/BasicEvaluatedExpression',
'webpack/lib/web/FetchCompileAsyncWasmPlugin.js', ],
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin', [
], 'webpack/lib/BasicEvaluatedExpression.js',
[ 'next/dist/compiled/webpack/BasicEvaluatedExpression',
'webpack/lib/ModuleFilenameHelpers', ],
'next/dist/compiled/webpack/ModuleFilenameHelpers', [
], 'webpack/lib/node/NodeTargetPlugin',
[ 'next/dist/compiled/webpack/NodeTargetPlugin',
'webpack/lib/ModuleFilenameHelpers.js', ],
'next/dist/compiled/webpack/ModuleFilenameHelpers', [
], 'webpack/lib/node/NodeTargetPlugin.js',
['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'], 'next/dist/compiled/webpack/NodeTargetPlugin',
['webpack/lib/GraphHelpers.js', 'next/dist/compiled/webpack/GraphHelpers'], ],
['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'], [
['webpack-sources', 'next/dist/compiled/webpack/sources'], 'webpack/lib/node/NodeTemplatePlugin',
['webpack-sources/lib', 'next/dist/compiled/webpack/sources'], 'next/dist/compiled/webpack/NodeTemplatePlugin',
['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'], ],
['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'], [
] 'webpack/lib/node/NodeTemplatePlugin.js',
'next/dist/compiled/webpack/NodeTemplatePlugin',
// Only bundled webpack needs require aliases. With `--custom-webpack`, ],
// webpack and webpack-sources resolve normally from the project. [
requireHook.addHookAliases( 'webpack/lib/LibraryTemplatePlugin',
[ 'next/dist/compiled/webpack/LibraryTemplatePlugin',
...(customWebpack ? [] : webpackAliases), ],
[
'webpack/lib/LibraryTemplatePlugin.js',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/SingleEntryPlugin',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/SingleEntryPlugin.js',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin.js',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin.js',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/ExternalsPlugin',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/ExternalsPlugin.js',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/ModuleFilenameHelpers',
'next/dist/compiled/webpack/ModuleFilenameHelpers',
],
[
'webpack/lib/ModuleFilenameHelpers.js',
'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-sources', '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.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 // Use dynamic require.resolve to avoid statically analyzable since they're only for build time
// 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(dir) loadWebpackHook()
} 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