Unverified Commit 1fa00686 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Disable esm resolving for appDir and alias react (#41687)

When esm package that depending on react is used between `pages/` and
`app/`, it's loading the user installed react through esm loader which
doesn't go through require hook, so we cannot intercept it with
require-hook.

Disable esm resolving when `appDir` is enabled for now, prefering to
pick the cjs bundle so that react import is intercepted by require hook
and pointing to the built-in react
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 48c7a801
...@@ -302,9 +302,31 @@ export default async function build( ...@@ -302,9 +302,31 @@ export default async function build(
const publicDir = path.join(dir, 'public') const publicDir = path.join(dir, 'public')
const isAppDirEnabled = !!config.experimental.appDir const isAppDirEnabled = !!config.experimental.appDir
const initialRequireHookFilePath = require.resolve(
'next/dist/server/initialize-require-hook'
)
const content = await promises.readFile(
initialRequireHookFilePath,
'utf8'
)
if (isAppDirEnabled) { if (isAppDirEnabled) {
process.env.NEXT_PREBUNDLED_REACT = '1' process.env.NEXT_PREBUNDLED_REACT = '1'
} }
await promises
.writeFile(
initialRequireHookFilePath,
content.replace(
/isPrebundled = (true|false)/,
`isPrebundled = ${isAppDirEnabled}`
)
)
.catch((err) => {
if (isAppDirEnabled) {
throw err
}
})
const { pagesDir, appDir } = findPagesDir(dir, isAppDirEnabled) const { pagesDir, appDir } = findPagesDir(dir, isAppDirEnabled)
const hasPublicDir = await fileExists(publicDir) const hasPublicDir = await fileExists(publicDir)
...@@ -342,7 +364,7 @@ export default async function build( ...@@ -342,7 +364,7 @@ export default async function build(
Log.info('Skipping validation of types') Log.info('Skipping validation of types')
} }
if (runLint && ignoreESLint) { if (runLint && ignoreESLint) {
// only print log when build requre lint while ignoreESLint is enabled // only print log when build require lint while ignoreESLint is enabled
Log.info('Skipping linting') Log.info('Skipping linting')
} }
......
...@@ -130,9 +130,9 @@ function isResourceInPackages(resource: string, packageNames?: string[]) { ...@@ -130,9 +130,9 @@ function isResourceInPackages(resource: string, packageNames?: string[]) {
const bundledReactImports = [ const bundledReactImports = [
'react', 'react',
'react-dom',
'react/jsx-runtime', 'react/jsx-runtime',
'react/jsx-dev-runtime', 'react/jsx-dev-runtime',
// 'react-dom',
'next/dist/compiled/react-server-dom-webpack/server.browser', 'next/dist/compiled/react-server-dom-webpack/server.browser',
] ]
...@@ -440,11 +440,12 @@ export const nextImageLoaderRegex = ...@@ -440,11 +440,12 @@ export const nextImageLoaderRegex =
/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i
export async function resolveExternal( export async function resolveExternal(
appDir: string, dir: string,
esmExternalsConfig: NextConfigComplete['experimental']['esmExternals'], esmExternalsConfig: NextConfigComplete['experimental']['esmExternals'],
context: string, context: string,
request: string, request: string,
isEsmRequested: boolean, isEsmRequested: boolean,
hasAppDir: boolean,
getResolve: ( getResolve: (
options: any options: any
) => ( ) => (
...@@ -466,6 +467,11 @@ export async function resolveExternal( ...@@ -466,6 +467,11 @@ export async function resolveExternal(
let preferEsmOptions = let preferEsmOptions =
esmExternals && isEsmRequested ? [true, false] : [false] esmExternals && isEsmRequested ? [true, false] : [false]
// Disable esm resolving for app/ and pages/ so for esm package using under pages/
// won't load react through esm loader
if (hasAppDir) {
preferEsmOptions = [false]
}
for (const preferEsm of preferEsmOptions) { for (const preferEsm of preferEsmOptions) {
const resolve = getResolve( const resolve = getResolve(
preferEsm ? esmResolveOptions : nodeResolveOptions preferEsm ? esmResolveOptions : nodeResolveOptions
...@@ -505,7 +511,7 @@ export async function resolveExternal( ...@@ -505,7 +511,7 @@ export async function resolveExternal(
const baseResolve = getResolve( const baseResolve = getResolve(
isEsm ? baseEsmResolveOptions : baseResolveOptions isEsm ? baseEsmResolveOptions : baseResolveOptions
) )
;[baseRes, baseIsEsm] = await baseResolve(appDir, request) ;[baseRes, baseIsEsm] = await baseResolve(dir, request)
} catch (err) { } catch (err) {
baseRes = null baseRes = null
baseIsEsm = false baseIsEsm = false
...@@ -1063,9 +1069,16 @@ export default async function getBaseWebpackConfig( ...@@ -1063,9 +1069,16 @@ export default async function getBaseWebpackConfig(
// Absolute requires (require('/foo')) are extremely uncommon, but // Absolute requires (require('/foo')) are extremely uncommon, but
// also have no need for customization as they're already resolved. // also have no need for customization as they're already resolved.
if (!isLocal) { if (!isLocal) {
if (/^(?:next$|react(?:$|\/)|react-dom(?:$|\/))/.test(request)) { if (/^(?:next$)/.test(request)) {
return `commonjs ${request}` return `commonjs ${request}`
} }
if (/^(react(?:$|\/)|react-dom(?:$|\/))/.test(request)) {
// override react-dom to server-rendering-stub for server
if (request === 'react-dom' && hasAppDir && !isClient) {
request = 'react-dom/server-rendering-stub'
}
return `commonjs ${hasAppDir ? 'next/dist/compiled/' : ''}${request}`
}
const notExternalModules = const notExternalModules =
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|legacy\/image|constants|dynamic|script|navigation|headers)$)|string-hash|private-next-rsc-mod-ref-proxy$)/ /^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|legacy\/image|constants|dynamic|script|navigation|headers)$)|string-hash|private-next-rsc-mod-ref-proxy$)/
...@@ -1082,6 +1095,7 @@ export default async function getBaseWebpackConfig( ...@@ -1082,6 +1095,7 @@ export default async function getBaseWebpackConfig(
// When in esm externals mode, and using import, we resolve with // When in esm externals mode, and using import, we resolve with
// ESM resolving options. // ESM resolving options.
// Also disable esm request when appDir is enabled
const isEsmRequested = dependencyType === 'esm' const isEsmRequested = dependencyType === 'esm'
const isLocalCallback = (localRes: string) => { const isLocalCallback = (localRes: string) => {
...@@ -1121,6 +1135,7 @@ export default async function getBaseWebpackConfig( ...@@ -1121,6 +1135,7 @@ export default async function getBaseWebpackConfig(
context, context,
request, request,
isEsmRequested, isEsmRequested,
hasAppDir,
getResolve, getResolve,
isLocal ? isLocalCallback : undefined isLocal ? isLocalCallback : undefined
) )
......
...@@ -643,6 +643,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -643,6 +643,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
context, context,
request, request,
isEsmRequested, isEsmRequested,
!!this.appDirEnabled,
(options) => (_: string, resRequest: string) => { (options) => (_: string, resRequest: string) => {
return getResolve(options)(parent, resRequest, job) return getResolve(options)(parent, resRequest, job)
}, },
......
import {
loadRequireHook,
overrideBuiltInReactPackages,
} from '../build/webpack/require-hook'
loadRequireHook()
const isPrebundled = false
if (isPrebundled) {
overrideBuiltInReactPackages()
}
import './initialize-require-hook'
import './node-polyfill-fetch' import './node-polyfill-fetch'
import './node-polyfill-web-streams' import './node-polyfill-web-streams'
...@@ -97,7 +98,6 @@ import { shouldUseReactRoot } from './utils' ...@@ -97,7 +98,6 @@ import { shouldUseReactRoot } from './utils'
import ResponseCache from './response-cache' import ResponseCache from './response-cache'
import { IncrementalCache } from './lib/incremental-cache' import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { loadRequireHook } from '../build/webpack/require-hook'
if (shouldUseReactRoot) { if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true' ;(process.env as any).__NEXT_REACT_ROOT = 'true'
...@@ -105,9 +105,6 @@ if (shouldUseReactRoot) { ...@@ -105,9 +105,6 @@ if (shouldUseReactRoot) {
import { renderToHTMLOrFlight as appRenderToHTMLOrFlight } from './app-render' import { renderToHTMLOrFlight as appRenderToHTMLOrFlight } from './app-render'
// require hook for custom server
loadRequireHook()
export * from './base-server' export * from './base-server'
type ExpressMiddleware = ( type ExpressMiddleware = (
......
import React from 'react' import React from 'react'
import Link from 'next/link' import Link from 'next/link'
import useSWR from 'swr'
import styles from '../styles/shared.module.css' import styles from '../styles/shared.module.css'
export default function Page(props) { export default function Page(props) {
const { data } = useSWR('swr-index', (v) => v, { fallbackData: 'swr-index' })
return ( return (
<> <>
<b>rc:{React.Component ? 'c' : 'no'}</b> <b>rc:{React.Component ? 'c' : 'no'}</b>
<p className={styles.content}>hello from pages/index</p> <p className={styles.content}>hello from pages/index</p>
<Link href="/dashboard">Dashboard</Link> <Link href="/dashboard">Dashboard</Link>
<div>{data}</div>
</> </>
) )
} }
...@@ -28,8 +28,9 @@ describe('app dir', () => { ...@@ -28,8 +28,9 @@ describe('app dir', () => {
next = await createNext({ next = await createNext({
files: new FileRef(path.join(__dirname, 'app')), files: new FileRef(path.join(__dirname, 'app')),
dependencies: { dependencies: {
react: 'experimental', swr: '2.0.0-rc.0',
'react-dom': 'experimental', react: 'latest',
'react-dom': 'latest',
sass: 'latest', sass: 'latest',
}, },
skipStart: true, skipStart: true,
...@@ -118,6 +119,9 @@ describe('app dir', () => { ...@@ -118,6 +119,9 @@ describe('app dir', () => {
it('should serve from pages', async () => { it('should serve from pages', async () => {
const html = await renderViaHTTP(next.url, '/') const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('hello from pages/index') expect(html).toContain('hello from pages/index')
// esm imports should work fine in pages/
expect(html).toContain('swr-index')
}) })
it('should serve dynamic route from pages', async () => { it('should serve dynamic route from pages', async () => {
......
Object.defineProperty(exports, '__esModule', { value: true })
exports.default = () => 'esm-export'
exports.named = 'named'
exports.value = 123
exports.array = [4, 5, 6]
exports.obj = { x: 1 }
{ {
"name": "non-isomorphic-text", "name": "non-isomorphic-text",
"type": "module", "exports": {
"exports": "./index.mjs", "import": "./index.mjs",
"require": "./index.js"
},
"browser": "./browser.js" "browser": "./browser.js"
} }
...@@ -19,6 +19,7 @@ describe('vercel analytics', () => { ...@@ -19,6 +19,7 @@ describe('vercel analytics', () => {
next = await createNext({ next = await createNext({
files: new FileRef(path.join(__dirname, 'app')), files: new FileRef(path.join(__dirname, 'app')),
dependencies: { dependencies: {
swr: '2.0.0-rc.0',
react: 'experimental', react: 'experimental',
'react-dom': 'experimental', 'react-dom': 'experimental',
sass: 'latest', sass: 'latest',
......
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