Unverified Commit d0d22ac6 authored by Ethan Arrowood's avatar Ethan Arrowood Committed by GitHub

Promote and rename server bundling options `serverComponentsExternalPackages`…

Promote and rename server bundling options `serverComponentsExternalPackages` and `bundlePagesExternals` (#65421)

This PR promotes and renames experimental configuration options related
to server bundling:
- `serverComponentsExternalPackages` -> `serverExternalPackages`
- `bundlePagesExternals` -> `bundlePagesRouterDependencies`

Existing docs for `serverComponentsExternalPackages` was changed. 
New docs for `bundlePagesRouterDependencies` were added.

Closes NEXT-3332
parent 2c31c79a
--- ---
title: serverComponentsExternalPackages title: serverExternalPackages
description: Opt-out specific dependencies from the Server Components bundling and use native Node.js `require`. description: Opt-out specific dependencies from the Server Components bundling and use native Node.js `require`.
--- ---
...@@ -10,9 +10,7 @@ If a dependency is using Node.js specific features, you can choose to opt-out sp ...@@ -10,9 +10,7 @@ If a dependency is using Node.js specific features, you can choose to opt-out sp
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: { serverExternalPackages: ['@acme/ui'],
serverComponentsExternalPackages: ['@acme/ui'],
},
} }
module.exports = nextConfig module.exports = nextConfig
......
---
title: bundlePagesRouterDependencies
description: Enable automatic dependency bundling for Pages Router
---
Enable automatic server-side dependency bundling for Pages Router applications. Matches the automatic dependency bundling in App Router.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
bundlePagesRouterDependencies: true,
}
module.exports = nextConfig
```
Explicitly opt-out certain packages from being bundled using the [`serverExternalPackages`](/docs/pages/api-reference/next-config-js/serverExternalPackages) option.
---
title: serverExternalPackages
description: Opt-out specific dependencies from the dependency bundling enabled by `bundlePagesRouterDependencies`.
---
Opt-out specific dependencies from being included in the automatic bundling of the [`bundlePagesRouterDependencies`](/docs/pages/api-reference/next-config-js/bundlePagesRouterDependencies) option.
These pages will then use native Node.js `require` to resolve the dependency.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
serverExternalPackages: ['@acme/ui'],
}
module.exports = nextConfig
```
Next.js includes a [short list of popular packages](https://github.com/vercel/next.js/blob/canary/packages/next/src/lib/server-external-packages.json) that currently are working on compatibility and automatically opt-ed out:
- `@appsignal/nodejs`
- `@aws-sdk/client-s3`
- `@aws-sdk/s3-presigned-post`
- `@blockfrost/blockfrost-js`
- `@highlight-run/node`
- `@jpg-store/lucid-cardano`
- `@libsql/client`
- `@mikro-orm/core`
- `@mikro-orm/knex`
- `@node-rs/argon2`
- `@node-rs/bcrypt`
- `@prisma/client`
- `@react-pdf/renderer`
- `@sentry/profiling-node`
- `@swc/core`
- `argon2`
- `autoprefixer`
- `aws-crt`
- `bcrypt`
- `better-sqlite3`
- `canvas`
- `cpu-features`
- `cypress`
- `eslint`
- `express`
- `firebase-admin`
- `isolated-vm`
- `jest`
- `jsdom`
- `libsql`
- `mdx-bundler`
- `mongodb`
- `mongoose`
- `next-mdx-remote`
- `next-seo`
- `node-pty`
- `node-web-audio-api`
- `oslo`
- `pg`
- `playwright`
- `postcss`
- `prettier`
- `prisma`
- `puppeteer-core`
- `puppeteer`
- `rimraf`
- `sharp`
- `shiki`
- `sqlite3`
- `tailwindcss`
- `ts-node`
- `typescript`
- `vscode-oniguruma`
- `undici`
- `webpack`
- `websocket`
- `zeromq`
...@@ -120,6 +120,9 @@ pub struct NextConfig { ...@@ -120,6 +120,9 @@ pub struct NextConfig {
typescript: TypeScriptConfig, typescript: TypeScriptConfig,
use_file_system_public_routes: bool, use_file_system_public_routes: bool,
webpack: Option<serde_json::Value>, webpack: Option<serde_json::Value>,
/// A list of packages that should be treated as external in the RSC server
/// build. @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/server_external_packages)
pub server_external_packages: Option<Vec<String>>,
} }
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
...@@ -460,9 +463,6 @@ pub struct ExperimentalConfig { ...@@ -460,9 +463,6 @@ pub struct ExperimentalConfig {
/// For use with `@next/mdx`. Compile MDX files using the new Rust compiler. /// For use with `@next/mdx`. Compile MDX files using the new Rust compiler.
/// @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs) /// @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs)
mdx_rs: Option<MdxRsOptions>, mdx_rs: Option<MdxRsOptions>,
/// A list of packages that should be treated as external in the RSC server
/// build. @see [api reference](https://nextjs.org/docs/app/api-reference/next-config-js/server_components_external_packages)
pub server_components_external_packages: Option<Vec<String>>,
pub strict_next_head: Option<bool>, pub strict_next_head: Option<bool>,
pub swc_plugins: Option<Vec<(String, serde_json::Value)>>, pub swc_plugins: Option<Vec<(String, serde_json::Value)>>,
pub turbo: Option<ExperimentalTurboConfig>, pub turbo: Option<ExperimentalTurboConfig>,
...@@ -737,11 +737,10 @@ impl NextConfig { ...@@ -737,11 +737,10 @@ impl NextConfig {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn server_component_externals(self: Vc<Self>) -> Result<Vc<Vec<String>>> { pub async fn server_external_packages(self: Vc<Self>) -> Result<Vc<Vec<String>>> {
Ok(Vc::cell( Ok(Vc::cell(
self.await? self.await?
.experimental .server_external_packages
.server_components_external_packages
.as_ref() .as_ref()
.cloned() .cloned()
.unwrap_or_default(), .unwrap_or_default(),
......
...@@ -140,12 +140,12 @@ pub async fn get_server_resolve_options_context( ...@@ -140,12 +140,12 @@ pub async fn get_server_resolve_options_context(
// Add the config's own list of external packages. // Add the config's own list of external packages.
external_packages.extend( external_packages.extend(
(*next_config.server_component_externals().await?) (*next_config.server_external_packages().await?)
.iter() .iter()
.cloned(), .cloned(),
); );
let server_component_externals_plugin = ExternalCjsModulesResolvePlugin::new( let server_external_packages_plugin = ExternalCjsModulesResolvePlugin::new(
project_path, project_path,
project_path.root(), project_path.root(),
ExternalPredicate::Only(Vc::cell(external_packages)).cell(), ExternalPredicate::Only(Vc::cell(external_packages)).cell(),
...@@ -196,7 +196,7 @@ pub async fn get_server_resolve_options_context( ...@@ -196,7 +196,7 @@ pub async fn get_server_resolve_options_context(
Vc::upcast(module_feature_report_resolve_plugin), Vc::upcast(module_feature_report_resolve_plugin),
Vc::upcast(unsupported_modules_resolve_plugin), Vc::upcast(unsupported_modules_resolve_plugin),
Vc::upcast(next_node_shared_runtime_plugin), Vc::upcast(next_node_shared_runtime_plugin),
Vc::upcast(server_component_externals_plugin), Vc::upcast(server_external_packages_plugin),
Vc::upcast(next_external_plugin), Vc::upcast(next_external_plugin),
] ]
} }
......
...@@ -233,9 +233,8 @@ impl ResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -233,9 +233,8 @@ impl ResolvePlugin for ExternalCjsModulesResolvePlugin {
"The request could not be resolved by Node.js from the importing module. The \ "The request could not be resolved by Node.js from the importing module. The \
way Node.js resolves modules is slightly different from the way Next.js \ way Node.js resolves modules is slightly different from the way Next.js \
resolves modules. Next.js was able to resolve it, while Node.js would not be \ resolves modules. Next.js was able to resolve it, while Node.js would not be \
able to.\nTry to remove this package from \ able to.\nTry to remove this package from serverExternalPackages.\nOr update \
serverComponentsExternalPackages.\nOr update the import side to use a \ the import side to use a compatible request that can be resolved by Node.js.",
compatible request that can be resolved by Node.js.",
); );
}; };
break result_from_original_location; break result_from_original_location;
...@@ -486,7 +485,7 @@ impl Issue for UnableToExternalize { ...@@ -486,7 +485,7 @@ impl Issue for UnableToExternalize {
StyledString::Text("Package ".to_string()), StyledString::Text("Package ".to_string()),
StyledString::Code(package), StyledString::Code(package),
StyledString::Text(" (".to_string()), StyledString::Text(" (".to_string()),
StyledString::Code("serverComponentsExternalPackages".to_string()), StyledString::Code("serverExternalPackages".to_string()),
StyledString::Text(" or default list) can't be external".to_string()), StyledString::Text(" or default list) can't be external".to_string()),
]) ])
.cell()) .cell())
...@@ -510,7 +509,7 @@ impl Issue for UnableToExternalize { ...@@ -510,7 +509,7 @@ impl Issue for UnableToExternalize {
StyledString::Text("The request ".to_string()), StyledString::Text("The request ".to_string()),
StyledString::Code(self.request.to_string()), StyledString::Code(self.request.to_string()),
StyledString::Text(" matches ".to_string()), StyledString::Text(" matches ".to_string()),
StyledString::Code("serverComponentsExternalPackages".to_string()), StyledString::Code("serverExternalPackages".to_string()),
StyledString::Text( StyledString::Text(
" (or the default list), but it can't be external:".to_string(), " (or the default list), but it can't be external:".to_string(),
), ),
......
...@@ -416,7 +416,7 @@ function resolveBundlingOptOutPackages({ ...@@ -416,7 +416,7 @@ function resolveBundlingOptOutPackages({
resolvedExternalPackageDirs resolvedExternalPackageDirs
) || ) ||
(isEsm && isAppLayer) || (isEsm && isAppLayer) ||
(!isAppLayer && config.experimental.bundlePagesExternals) (!isAppLayer && config.bundlePagesRouterDependencies)
if (nodeModulesRegex.test(resolvedRes)) { if (nodeModulesRegex.test(resolvedRes)) {
const isOptOutBundling = optOutBundlingPackageRegex.test(resolvedRes) const isOptOutBundling = optOutBundlingPackageRegex.test(resolvedRes)
......
...@@ -775,18 +775,15 @@ export default async function getBaseWebpackConfig( ...@@ -775,18 +775,15 @@ export default async function getBaseWebpackConfig(
const crossOrigin = config.crossOrigin const crossOrigin = config.crossOrigin
// The `serverComponentsExternalPackages` should not conflict with // The `serverExternalPackages` should not conflict with
// the `transpilePackages`. // the `transpilePackages`.
if ( if (config.serverExternalPackages && finalTranspilePackages) {
config.experimental.serverComponentsExternalPackages &&
finalTranspilePackages
) {
const externalPackageConflicts = finalTranspilePackages.filter((pkg) => const externalPackageConflicts = finalTranspilePackages.filter((pkg) =>
config.experimental.serverComponentsExternalPackages?.includes(pkg) config.serverExternalPackages?.includes(pkg)
) )
if (externalPackageConflicts.length > 0) { if (externalPackageConflicts.length > 0) {
throw new Error( throw new Error(
`The packages specified in the 'transpilePackages' conflict with the 'serverComponentsExternalPackages': ${externalPackageConflicts.join( `The packages specified in the 'transpilePackages' conflict with the 'serverExternalPackages': ${externalPackageConflicts.join(
', ' ', '
)}` )}`
) )
...@@ -795,7 +792,7 @@ export default async function getBaseWebpackConfig( ...@@ -795,7 +792,7 @@ export default async function getBaseWebpackConfig(
// For original request, such as `package name` // For original request, such as `package name`
const optOutBundlingPackages = EXTERNAL_PACKAGES.concat( const optOutBundlingPackages = EXTERNAL_PACKAGES.concat(
...(config.experimental.serverComponentsExternalPackages || []) ...(config.serverExternalPackages || [])
).filter((pkg) => !finalTranspilePackages?.includes(pkg)) ).filter((pkg) => !finalTranspilePackages?.includes(pkg))
// For resolved request, such as `absolute path/package name/foo/bar.js` // For resolved request, such as `absolute path/package name/foo/bar.js`
const optOutBundlingPackageRegex = new RegExp( const optOutBundlingPackageRegex = new RegExp(
......
...@@ -32,7 +32,6 @@ const unsupportedTurbopackNextConfigOptions = [ ...@@ -32,7 +32,6 @@ const unsupportedTurbopackNextConfigOptions = [
'experimental.adjustFontFallbacks', 'experimental.adjustFontFallbacks',
'experimental.adjustFontFallbacksWithSizeAdjust', 'experimental.adjustFontFallbacksWithSizeAdjust',
'experimental.allowedRevalidateHeaderKeys', 'experimental.allowedRevalidateHeaderKeys',
'experimental.bundlePagesExternals',
'experimental.extensionAlias', 'experimental.extensionAlias',
'experimental.fallbackNodePolyfills', 'experimental.fallbackNodePolyfills',
......
...@@ -133,6 +133,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -133,6 +133,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
assetPrefix: z.string().optional(), assetPrefix: z.string().optional(),
basePath: z.string().optional(), basePath: z.string().optional(),
bundlePagesRouterDependencies: z.boolean().optional(),
cacheHandler: z.string().min(1).optional(), cacheHandler: z.string().min(1).optional(),
cacheMaxMemorySize: z.number().optional(), cacheMaxMemorySize: z.number().optional(),
cleanDistDir: z.boolean().optional(), cleanDistDir: z.boolean().optional(),
...@@ -320,7 +321,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -320,7 +321,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
taint: z.boolean().optional(), taint: z.boolean().optional(),
prerenderEarlyExit: z.boolean().optional(), prerenderEarlyExit: z.boolean().optional(),
proxyTimeout: z.number().gte(0).optional(), proxyTimeout: z.number().gte(0).optional(),
serverComponentsExternalPackages: z.array(z.string()).optional(),
scrollRestoration: z.boolean().optional(), scrollRestoration: z.boolean().optional(),
sri: z sri: z
.object({ .object({
...@@ -414,7 +414,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -414,7 +414,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
serverMinification: z.boolean().optional(), serverMinification: z.boolean().optional(),
serverSourceMaps: z.boolean().optional(), serverSourceMaps: z.boolean().optional(),
bundlePagesExternals: z.boolean().optional(),
staticWorkerRequestDeduping: z.boolean().optional(), staticWorkerRequestDeduping: z.boolean().optional(),
useWasmBinary: z.boolean().optional(), useWasmBinary: z.boolean().optional(),
useLightningcss: z.boolean().optional(), useLightningcss: z.boolean().optional(),
...@@ -571,6 +570,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -571,6 +570,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
// saas option is unknown, use z.any() here // saas option is unknown, use z.any() here
sassOptions: z.record(z.string(), z.any()).optional(), sassOptions: z.record(z.string(), z.any()).optional(),
serverExternalPackages: z.array(z.string()).optional(),
serverRuntimeConfig: z.record(z.string(), z.any()).optional(), serverRuntimeConfig: z.record(z.string(), z.any()).optional(),
skipMiddlewareUrlNormalize: z.boolean().optional(), skipMiddlewareUrlNormalize: z.boolean().optional(),
skipTrailingSlashRedirect: z.boolean().optional(), skipTrailingSlashRedirect: z.boolean().optional(),
......
...@@ -279,12 +279,6 @@ export interface ExperimentalConfig { ...@@ -279,12 +279,6 @@ export interface ExperimentalConfig {
adjustFontFallbacks?: boolean adjustFontFallbacks?: boolean
adjustFontFallbacksWithSizeAdjust?: boolean adjustFontFallbacksWithSizeAdjust?: boolean
/**
* A list of packages that should be treated as external in the RSC server build.
* @see https://nextjs.org/docs/app/api-reference/next-config-js/serverComponentsExternalPackages
*/
serverComponentsExternalPackages?: string[]
webVitalsAttribution?: Array<(typeof WEB_VITALS)[number]> webVitalsAttribution?: Array<(typeof WEB_VITALS)[number]>
/** /**
...@@ -420,10 +414,7 @@ export interface ExperimentalConfig { ...@@ -420,10 +414,7 @@ export interface ExperimentalConfig {
* @internal Used by the Next.js internals only. * @internal Used by the Next.js internals only.
*/ */
trustHostHeader?: boolean trustHostHeader?: boolean
/**
* Enables the bundling of node_modules packages (externals) for pages server-side bundles.
*/
bundlePagesExternals?: boolean
/** /**
* Uses an IPC server to dedupe build-time requests to the cache handler * Uses an IPC server to dedupe build-time requests to the cache handler
*/ */
...@@ -838,6 +829,17 @@ export interface NextConfig extends Record<string, any> { ...@@ -838,6 +829,17 @@ export interface NextConfig extends Record<string, any> {
* Enable experimental features. Note that all experimental features are subject to breaking changes in the future. * Enable experimental features. Note that all experimental features are subject to breaking changes in the future.
*/ */
experimental?: ExperimentalConfig experimental?: ExperimentalConfig
/**
* Enables the bundling of node_modules packages (externals) for pages server-side bundles.
*/
bundlePagesRouterDependencies?: boolean
/**
* A list of packages that should be treated as external in the RSC server build.
* @see https://nextjs.org/docs/app/api-reference/next-config-js/serverExternalPackages
*/
serverExternalPackages?: string[]
} }
export const defaultConfig: NextConfig = { export const defaultConfig: NextConfig = {
...@@ -942,7 +944,6 @@ export const defaultConfig: NextConfig = { ...@@ -942,7 +944,6 @@ export const defaultConfig: NextConfig = {
turbotrace: undefined, turbotrace: undefined,
typedRoutes: false, typedRoutes: false,
instrumentationHook: false, instrumentationHook: false,
bundlePagesExternals: false,
parallelServerCompiles: false, parallelServerCompiles: false,
parallelServerBuildTraces: false, parallelServerBuildTraces: false,
ppr: ppr:
...@@ -963,6 +964,7 @@ export const defaultConfig: NextConfig = { ...@@ -963,6 +964,7 @@ export const defaultConfig: NextConfig = {
static: 300, static: 300,
}, },
}, },
bundlePagesRouterDependencies: false,
} }
export async function normalizeConfig(phase: string, config: any) { export async function normalizeConfig(phase: string, config: any) {
......
...@@ -3,43 +3,62 @@ const path = require('path') ...@@ -3,43 +3,62 @@ const path = require('path')
const serverExternals = require('../packages/next/src/lib/server-external-packages.json') const serverExternals = require('../packages/next/src/lib/server-external-packages.json')
const docPath = `docs/02-app/02-api-reference/05-next-config-js/serverComponentsExternalPackages.mdx` function validate(docPath) {
const docContent = fs.readFileSync(path.join(__dirname, '..', docPath), 'utf8') const docContent = fs.readFileSync(
path.join(__dirname, '..', docPath),
'utf8'
)
const docPkgs = []
const extraPkgs = []
const missingPkgs = []
const docPkgs = [] for (let docPkg of docContent.split('opt-ed out:').pop().split('\n')) {
const extraPkgs = [] docPkg = docPkg.split('`')[1]
const missingPkgs = []
for (let docPkg of docContent.split('opt-ed out:').pop().split('\n')) { if (!docPkg) {
docPkg = docPkg.split('`')[1] continue
}
docPkgs.push(docPkg)
if (!docPkg) { if (!serverExternals.includes(docPkg)) {
continue extraPkgs.push(docPkg)
}
} }
docPkgs.push(docPkg)
if (!serverExternals.includes(docPkg)) { for (const pkg of serverExternals) {
extraPkgs.push(docPkg) if (!docPkgs.includes(pkg)) {
missingPkgs.push(pkg)
}
} }
}
for (const pkg of serverExternals) { if (extraPkgs.length || missingPkgs.length) {
if (!docPkgs.includes(pkg)) { console.log(
missingPkgs.push(pkg) 'server externals doc out of sync!\n' +
`Extra packages included: ` +
JSON.stringify(extraPkgs, null, 2) +
'\n' +
`Missing packages: ` +
JSON.stringify(missingPkgs, null, 2) +
'\n' +
`doc path: ${docPath}`
)
return false
} }
return true
} }
if (extraPkgs.length || missingPkgs.length) { const appRouterValid = validate(
console.log( `docs/02-app/02-api-reference/05-next-config-js/serverExternalPackages.mdx`
'server externals doc out of sync!\n' + )
`Extra packages included: ` + const pagesRouterValid = validate(
JSON.stringify(extraPkgs, null, 2) + `docs/03-pages/02-api-reference/03-next-config-js/serverExternalPackages.mdx`
'\n' + )
`Missing packages: ` +
JSON.stringify(missingPkgs, null, 2) + if (appRouterValid && pagesRouterValid) {
'\n' + console.log('server externals doc is in sync')
`doc path: ${docPath}` process.exit(0)
) } else {
process.exit(1) process.exit(1)
} }
console.log('server externals doc is in sync')
module.exports = { module.exports = {
reactStrictMode: true, reactStrictMode: true,
transpilePackages: ['css', 'font', 'transpile-ts-lib', 'transpile-cjs-lib'], transpilePackages: ['css', 'font', 'transpile-ts-lib', 'transpile-cjs-lib'],
experimental: { serverExternalPackages: ['conditional-exports-optout', 'dual-pkg-optout'],
serverComponentsExternalPackages: [
'conditional-exports-optout',
'dual-pkg-optout',
],
},
} }
...@@ -3,9 +3,7 @@ module.exports = { ...@@ -3,9 +3,7 @@ module.exports = {
onDemandEntries: { onDemandEntries: {
maxInactiveAge: 1000 * 60 * 60, maxInactiveAge: 1000 * 60 * 60,
}, },
experimental: { serverExternalPackages: ['conditional-exports-optout'],
serverComponentsExternalPackages: ['conditional-exports-optout'],
},
rewrites: async () => { rewrites: async () => {
return { return {
afterFiles: [ afterFiles: [
......
...@@ -6,7 +6,7 @@ describe('app-dir - server components externals', () => { ...@@ -6,7 +6,7 @@ describe('app-dir - server components externals', () => {
files: __dirname, files: __dirname,
}) })
it('should have externals for those in config.experimental.serverComponentsExternalPackages', async () => { it('should have externals for those in config.serverExternalPackages', async () => {
const $ = await next.render$('/') const $ = await next.render$('/')
const text = $('#directory').text() const text = $('#directory').text()
...@@ -28,7 +28,7 @@ describe('app-dir - server components externals', () => { ...@@ -28,7 +28,7 @@ describe('app-dir - server components externals', () => {
// Inspect webpack server bundles // Inspect webpack server bundles
if (!isTurbopack) { if (!isTurbopack) {
it('should externalize serverComponentsExternalPackages for server rendering layer', async () => { it('should externalize serversExternalPackages for server rendering layer', async () => {
await next.fetch('/client') await next.fetch('/client')
const ssrBundle = await next.readFile('.next/server/app/client/page.js') const ssrBundle = await next.readFile('.next/server/app/client/page.js')
expect(ssrBundle).not.toContain('external-package-mark:index') expect(ssrBundle).not.toContain('external-package-mark:index')
......
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {
experimental: { serverExternalPackages: ['external-package'],
serverComponentsExternalPackages: ['external-package'],
},
} }
module.exports = nextConfig module.exports = nextConfig
...@@ -5,12 +5,12 @@ module.exports = { ...@@ -5,12 +5,12 @@ module.exports = {
'preact/compat': 'react', 'preact/compat': 'react',
}, },
}, },
serverComponentsExternalPackages: [
'app-esm-package1',
'app-esm-package2',
'app-cjs-esm-package',
],
}, },
serverExternalPackages: [
'app-esm-package1',
'app-esm-package2',
'app-cjs-esm-package',
],
webpack(config, { isServer }) { webpack(config, { isServer }) {
config.resolve.alias = { config.resolve.alias = {
...config.resolve.alias, ...config.resolve.alias,
......
module.exports = { module.exports = {
experimental: { bundlePagesRouterDependencies: true,
bundlePagesExternals: true, serverExternalPackages: ['opted-out-external-package'],
serverComponentsExternalPackages: ['opted-out-external-package'],
},
} }
...@@ -6,7 +6,7 @@ import { nextBuild } from 'next-test-utils' ...@@ -6,7 +6,7 @@ import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
describe('bundle pages externals with config.experimental.bundlePagesExternals', () => { describe('bundle pages externals with config.bundlePagesRouterDependencies', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
...@@ -21,7 +21,7 @@ describe('bundle pages externals with config.experimental.bundlePagesExternals', ...@@ -21,7 +21,7 @@ describe('bundle pages externals with config.experimental.bundlePagesExternals',
expect(output).not.toContain('require("external-package")') expect(output).not.toContain('require("external-package")')
}) })
it('should respect the serverComponentsExternals config', async () => { it('should respect the serverExternalPackages config', async () => {
const output = await fs.readFile( const output = await fs.readFile(
join(appDir, '.next/server/pages/index.js'), join(appDir, '.next/server/pages/index.js'),
'utf8' 'utf8'
......
...@@ -3283,8 +3283,8 @@ ...@@ -3283,8 +3283,8 @@
}, },
"test/e2e/app-dir/server-components-externals/index.test.ts": { "test/e2e/app-dir/server-components-externals/index.test.ts": {
"passed": [ "passed": [
"app-dir - server components externals should externalize serverComponentsExternalPackages for server rendering layer", "app-dir - server components externals should externalize serverExternalPackages for server rendering layer",
"app-dir - server components externals should have externals for those in config.experimental.serverComponentsExternalPackages", "app-dir - server components externals should have externals for those in config.serverExternalPackages",
"app-dir - server components externals uses externals for predefined list in server-external-packages.json" "app-dir - server components externals uses externals for predefined list in server-external-packages.json"
], ],
"failed": [], "failed": [],
...@@ -8481,8 +8481,8 @@ ...@@ -8481,8 +8481,8 @@
"test/integration/externals-pages-bundle/test/index.test.js": { "test/integration/externals-pages-bundle/test/index.test.js": {
"passed": [], "passed": [],
"failed": [ "failed": [
"bundle pages externals with config.experimental.bundlePagesExternals production mode should have no externals with the config set", "bundle pages externals with config.bundlePagesRouterDependencies production mode should have no externals with the config set",
"bundle pages externals with config.experimental.bundlePagesExternals production mode should respect the serverComponentsExternals config" "bundle pages externals with config.bundlePagesRouterDependencies production mode should respect the serverExternalPackages config"
], ],
"pending": [], "pending": [],
"flakey": [], "flakey": [],
...@@ -5367,7 +5367,7 @@ ...@@ -5367,7 +5367,7 @@
}, },
"test/e2e/app-dir/server-components-externals/index.test.ts": { "test/e2e/app-dir/server-components-externals/index.test.ts": {
"passed": [ "passed": [
"app-dir - server components externals should have externals for those in config.experimental.serverComponentsExternalPackages", "app-dir - server components externals should have externals for those in config.serverExternalPackages",
"app-dir - server components externals uses externals for predefined list in server-external-packages.json" "app-dir - server components externals uses externals for predefined list in server-external-packages.json"
], ],
"failed": [], "failed": [],
...@@ -10497,8 +10497,8 @@ ...@@ -10497,8 +10497,8 @@
"passed": [], "passed": [],
"failed": [], "failed": [],
"pending": [ "pending": [
"bundle pages externals with config.experimental.bundlePagesExternals production mode should have no externals with the config set", "bundle pages externals with config.bundlePagesRouterDependencies production mode should have no externals with the config set",
"bundle pages externals with config.experimental.bundlePagesExternals production mode should respect the serverComponentsExternals config" "bundle pages externals with config.bundlePagesRouterDependencies production mode should respect the serverExternalsPackages config"
], ],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
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