Unverified Commit 2874bc06 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix server output bundling packages module resolving (#59369)

parent 42ec6c89
...@@ -47,6 +47,7 @@ export async function resolveExternal( ...@@ -47,6 +47,7 @@ export async function resolveExternal(
context: string, context: string,
request: string, request: string,
isEsmRequested: boolean, isEsmRequested: boolean,
optOutBundlingPackages: string[],
getResolve: ( getResolve: (
options: any options: any
) => ( ) => (
...@@ -66,8 +67,15 @@ export async function resolveExternal( ...@@ -66,8 +67,15 @@ export async function resolveExternal(
let res: string | null = null let res: string | null = null
let isEsm: boolean = false let isEsm: boolean = false
let preferEsmOptions = const preferEsmOptions =
esmExternals && isEsmRequested ? [true, false] : [false] esmExternals &&
isEsmRequested &&
// For package that marked as externals that should be not bundled,
// we don't resolve them as ESM since it could be resolved as async module,
// such as `import(external package)` in the bundle, valued as a `Promise`.
!optOutBundlingPackages.some((optOut) => request.startsWith(optOut))
? [true, false]
: [false]
for (const preferEsm of preferEsmOptions) { for (const preferEsm of preferEsmOptions) {
const resolve = getResolve( const resolve = getResolve(
...@@ -131,10 +139,12 @@ export async function resolveExternal( ...@@ -131,10 +139,12 @@ export async function resolveExternal(
export function makeExternalHandler({ export function makeExternalHandler({
config, config,
optOutBundlingPackages,
optOutBundlingPackageRegex, optOutBundlingPackageRegex,
dir, dir,
}: { }: {
config: NextConfigComplete config: NextConfigComplete
optOutBundlingPackages: string[]
optOutBundlingPackageRegex: RegExp optOutBundlingPackageRegex: RegExp
dir: string dir: string
}) { }) {
...@@ -289,6 +299,7 @@ export function makeExternalHandler({ ...@@ -289,6 +299,7 @@ export function makeExternalHandler({
context, context,
request, request,
isEsmRequested, isEsmRequested,
optOutBundlingPackages,
getResolve, getResolve,
isLocal ? resolveNextExternal : undefined isLocal ? resolveNextExternal : undefined
) )
...@@ -349,6 +360,7 @@ export function makeExternalHandler({ ...@@ -349,6 +360,7 @@ export function makeExternalHandler({
context, context,
pkg + '/package.json', pkg + '/package.json',
isEsmRequested, isEsmRequested,
optOutBundlingPackages,
getResolve, getResolve,
isLocal ? resolveNextExternal : undefined isLocal ? resolveNextExternal : undefined
) )
......
...@@ -727,9 +727,11 @@ export default async function getBaseWebpackConfig( ...@@ -727,9 +727,11 @@ export default async function getBaseWebpackConfig(
const crossOrigin = config.crossOrigin const crossOrigin = config.crossOrigin
// For original request, such as `package name`
const optOutBundlingPackages = EXTERNAL_PACKAGES.concat( const optOutBundlingPackages = EXTERNAL_PACKAGES.concat(
...(config.experimental.serverComponentsExternalPackages || []) ...(config.experimental.serverComponentsExternalPackages || [])
) )
// For resolved request, such as `absolute path/package name/foo/bar.js`
const optOutBundlingPackageRegex = new RegExp( const optOutBundlingPackageRegex = new RegExp(
`[/\\\\]node_modules[/\\\\](${optOutBundlingPackages `[/\\\\]node_modules[/\\\\](${optOutBundlingPackages
.map((p) => p.replace(/\//g, '[/\\\\]')) .map((p) => p.replace(/\//g, '[/\\\\]'))
...@@ -738,6 +740,7 @@ export default async function getBaseWebpackConfig( ...@@ -738,6 +740,7 @@ export default async function getBaseWebpackConfig(
const handleExternals = makeExternalHandler({ const handleExternals = makeExternalHandler({
config, config,
optOutBundlingPackages,
optOutBundlingPackageRegex, optOutBundlingPackageRegex,
dir, dir,
}) })
...@@ -1662,6 +1665,7 @@ export default async function getBaseWebpackConfig( ...@@ -1662,6 +1665,7 @@ export default async function getBaseWebpackConfig(
outputFileTracingRoot: config.experimental.outputFileTracingRoot, outputFileTracingRoot: config.experimental.outputFileTracingRoot,
appDirEnabled: hasAppDir, appDirEnabled: hasAppDir,
turbotrace: config.experimental.turbotrace, turbotrace: config.experimental.turbotrace,
optOutBundlingPackages,
traceIgnores: config.experimental.outputFileTracingIgnores || [], traceIgnores: config.experimental.outputFileTracingIgnores || [],
} }
), ),
......
...@@ -133,6 +133,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -133,6 +133,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
private rootDir: string private rootDir: string
private appDir: string | undefined private appDir: string | undefined
private pagesDir: string | undefined private pagesDir: string | undefined
private optOutBundlingPackages: string[]
private appDirEnabled?: boolean private appDirEnabled?: boolean
private tracingRoot: string private tracingRoot: string
private entryTraces: Map<string, Set<string>> private entryTraces: Map<string, Set<string>>
...@@ -144,6 +145,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -144,6 +145,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
rootDir, rootDir,
appDir, appDir,
pagesDir, pagesDir,
optOutBundlingPackages,
appDirEnabled, appDirEnabled,
traceIgnores, traceIgnores,
esmExternals, esmExternals,
...@@ -153,6 +155,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -153,6 +155,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
rootDir: string rootDir: string
appDir: string | undefined appDir: string | undefined
pagesDir: string | undefined pagesDir: string | undefined
optOutBundlingPackages: string[]
appDirEnabled?: boolean appDirEnabled?: boolean
traceIgnores?: string[] traceIgnores?: string[]
outputFileTracingRoot?: string outputFileTracingRoot?: string
...@@ -168,6 +171,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -168,6 +171,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
this.traceIgnores = traceIgnores || [] this.traceIgnores = traceIgnores || []
this.tracingRoot = outputFileTracingRoot || rootDir this.tracingRoot = outputFileTracingRoot || rootDir
this.turbotrace = turbotrace this.turbotrace = turbotrace
this.optOutBundlingPackages = optOutBundlingPackages
} }
// Here we output all traced assets and webpack chunks to a // Here we output all traced assets and webpack chunks to a
...@@ -743,6 +747,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -743,6 +747,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
context, context,
request, request,
isEsmRequested, isEsmRequested,
this.optOutBundlingPackages,
(options) => (_: string, resRequest: string) => { (options) => (_: string, resRequest: string) => {
return getResolve(options)(parent, resRequest, job) return getResolve(options)(parent, resRequest, job)
}, },
......
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { shouldRunTurboDevTest } from '../../../lib/next-test-utils' import { check, shouldRunTurboDevTest } from 'next-test-utils'
async function resolveStreamResponse(response: any, onData?: any) { async function resolveStreamResponse(response: any, onData?: any) {
let result = '' let result = ''
...@@ -250,5 +250,22 @@ createNextDescribe( ...@@ -250,5 +250,22 @@ createNextDescribe(
const html = await next.render('/async-storage') const html = await next.render('/async-storage')
expect(html).toContain('success') expect(html).toContain('success')
}) })
it('should not prefer to resolve esm over cjs for bundling optout packages', async () => {
const browser = await next.browser('/optout/action')
expect(await browser.elementByCss('#dual-pkg-outout p').text()).toBe('')
browser.elementByCss('#dual-pkg-outout button').click()
await check(async () => {
const text = await browser.elementByCss('#dual-pkg-outout p').text()
if (process.env.TURBOPACK) {
// The prefer esm won't effect turbopack resolving
expect(text).toBe('dual-pkg-optout:mjs')
} else {
expect(text).toBe('dual-pkg-optout:cjs')
}
return 'success'
}, /success/)
})
} }
) )
'use server'
import { value as dualPkgOptoutValue } from 'dual-pkg-optout'
export async function getDualOptoutValue() {
return dualPkgOptoutValue
}
'use client'
import { useState } from 'react'
import { getDualOptoutValue } from './actions'
export default function Page() {
const [optoutDisplayValue, setOptoutDisplayValue] = useState('')
return (
<div id="dual-pkg-outout">
<p>{optoutDisplayValue}</p>
<button
onClick={async () => {
setOptoutDisplayValue(await getDualOptoutValue())
}}
>
dual-pkg-optout
</button>
</div>
)
}
...@@ -2,6 +2,9 @@ module.exports = { ...@@ -2,6 +2,9 @@ module.exports = {
reactStrictMode: true, reactStrictMode: true,
transpilePackages: ['untranspiled-module', 'css', 'font'], transpilePackages: ['untranspiled-module', 'css', 'font'],
experimental: { experimental: {
serverComponentsExternalPackages: ['conditional-exports-optout'], serverComponentsExternalPackages: [
'conditional-exports-optout',
'dual-pkg-optout',
],
}, },
} }
{
"exports": {
"import": "./index.mjs",
"require": "./index.cjs"
}
}
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