Unverified Commit 3174c730 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Alias next public api to esm on edge runtime (#42709)

Cases like `next/link` and `next/router` imports are not alias since
they're not matching the existing alias pattern setting for edge
runtime, which causes router-context being bundled twice (both with cjs
and esm) into edge worker bundle.
so we resolve their paths and alias them to esm bundle for webpack
bundling.

Other minor changes:

* update `require` calls to `import` expressions in edge ssr loaders
* remove client layer for apps without `appDir` enabled
* export `type` for ts typings in next/image to avoid alias to break
resolving

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`
parent 2c199c4c
...@@ -207,7 +207,7 @@ export function getEdgeServerEntry(opts: { ...@@ -207,7 +207,7 @@ export function getEdgeServerEntry(opts: {
// The Edge bundle includes the server in its entrypoint, so it has to // The Edge bundle includes the server in its entrypoint, so it has to
// be in the SSR layer — we later convert the page request to the RSC layer // be in the SSR layer — we later convert the page request to the RSC layer
// via a webpack rule. // via a webpack rule.
layer: WEBPACK_LAYERS.client, layer: opts.appDirLoader ? WEBPACK_LAYERS.client : undefined,
} }
} }
......
...@@ -887,6 +887,21 @@ export default async function getBaseWebpackConfig( ...@@ -887,6 +887,21 @@ export default async function getBaseWebpackConfig(
'next/dist/client': 'next/dist/esm/client', 'next/dist/client': 'next/dist/esm/client',
'next/dist/shared': 'next/dist/esm/shared', 'next/dist/shared': 'next/dist/esm/shared',
'next/dist/pages': 'next/dist/esm/pages', 'next/dist/pages': 'next/dist/esm/pages',
'next/dist/lib': 'next/dist/esm/lib',
// Alias the usage of next public APIs
[require.resolve('next/dist/client/link')]:
'next/dist/esm/client/link',
[require.resolve('next/dist/client/image')]:
'next/dist/esm/client/image',
[require.resolve('next/dist/client/script')]:
'next/dist/esm/client/script',
[require.resolve('next/dist/client/router')]:
'next/dist/esm/client/router',
[require.resolve('next/dist/shared/lib/head')]:
'next/dist/esm/shared/lib/head',
[require.resolve('next/dist/shared/lib/dynamic')]:
'next/dist/esm/shared/lib/dynamic',
} }
: undefined), : undefined),
...@@ -1128,7 +1143,7 @@ export default async function getBaseWebpackConfig( ...@@ -1128,7 +1143,7 @@ export default async function getBaseWebpackConfig(
// Treat next internals as non-external for server layer // Treat next internals as non-external for server layer
layer === WEBPACK_LAYERS.server layer === WEBPACK_LAYERS.server
? false ? false
: /next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test( : /next[/\\]dist[/\\](esm[\\/])?(shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
localRes localRes
) )
...@@ -1194,7 +1209,9 @@ export default async function getBaseWebpackConfig( ...@@ -1194,7 +1209,9 @@ export default async function getBaseWebpackConfig(
const externalType = isEsm ? 'module' : 'commonjs' const externalType = isEsm ? 'module' : 'commonjs'
if ( if (
/next[/\\]dist[/\\]shared[/\\](?!lib[/\\]router[/\\]router)/.test(res) || /next[/\\]dist[/\\](esm[\\/])?shared[/\\](?!lib[/\\]router[/\\]router)/.test(
res
) ||
/next[/\\]dist[/\\]compiled[/\\].*\.[mc]?js$/.test(res) /next[/\\]dist[/\\]compiled[/\\].*\.[mc]?js$/.test(res)
) { ) {
return `${externalType} ${request}` return `${externalType} ${request}`
......
...@@ -97,28 +97,29 @@ export default async function edgeSSRLoader(this: any) { ...@@ -97,28 +97,29 @@ export default async function edgeSSRLoader(this: any) {
${ ${
isAppDir isAppDir
? ` ? `
import { renderToHTMLOrFlight as appRenderToHTML } from 'next/dist/esm/server/app-render'
import * as pageMod from ${JSON.stringify(pageModPath)}
const Document = null const Document = null
const appRenderToHTML = require('next/dist/esm/server/app-render').renderToHTMLOrFlight
const pagesRenderToHTML = null const pagesRenderToHTML = null
const pageMod = require(${JSON.stringify(pageModPath)})
const appMod = null const appMod = null
const errorMod = null const errorMod = null
const error500Mod = null const error500Mod = null
` `
: ` : `
const Document = require(${stringifiedDocumentPath}).default import Document from ${stringifiedDocumentPath}
const appRenderToHTML = null import { renderToHTML as pagesRenderToHTML } from 'next/dist/esm/server/render'
const pagesRenderToHTML = require('next/dist/esm/server/render').renderToHTML import * as pageMod from ${stringifiedPagePath}
const pageMod = require(${stringifiedPagePath}) import * as appMod from ${stringifiedAppPath}
const appMod = require(${stringifiedAppPath}) import * as errorMod from ${stringifiedErrorPath}
const errorMod = require(${stringifiedErrorPath}) ${
const error500Mod = ${ stringified500Path
stringified500Path ? `require(${stringified500Path})` : 'null' ? `import * as error500Mod from ${stringified500Path}`
: `const error500Mod = null`
} }
const appRenderToHTML = null
` `
} }
const buildManifest = self.__BUILD_MANIFEST const buildManifest = self.__BUILD_MANIFEST
const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST
const rscManifest = self.__RSC_MANIFEST const rscManifest = self.__RSC_MANIFEST
......
...@@ -119,7 +119,7 @@ function handleWarnings(warnings) { ...@@ -119,7 +119,7 @@ function handleWarnings(warnings) {
}) })
if (typeof console !== 'undefined' && typeof console.warn === 'function') { if (typeof console !== 'undefined' && typeof console.warn === 'function') {
for (let i = 0; i < formatted.warnings.length; i++) { for (let i = 0; i < formatted.warnings?.length; i++) {
if (i === 5) { if (i === 5) {
console.warn( console.warn(
'There were more warnings in other files.\n' + 'There were more warnings in other files.\n' +
......
...@@ -10,12 +10,12 @@ import React, { ...@@ -10,12 +10,12 @@ import React, {
} from 'react' } from 'react'
import Head from '../shared/lib/head' import Head from '../shared/lib/head'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg' import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import { import type {
ImageConfigComplete, ImageConfigComplete,
imageConfigDefault,
ImageLoaderProps, ImageLoaderProps,
ImageLoaderPropsWithConfig, ImageLoaderPropsWithConfig,
} from '../shared/lib/image-config' } from '../shared/lib/image-config'
import { imageConfigDefault } from '../shared/lib/image-config'
import { ImageConfigContext } from '../shared/lib/image-config-context' import { ImageConfigContext } from '../shared/lib/image-config-context'
import { warnOnce } from '../shared/lib/utils/warn-once' import { warnOnce } from '../shared/lib/utils/warn-once'
// @ts-ignore - This is replaced by webpack alias // @ts-ignore - This is replaced by webpack alias
...@@ -36,7 +36,7 @@ const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const ...@@ -36,7 +36,7 @@ const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number] type LoadingValue = typeof VALID_LOADING_VALUES[number]
type ImageConfig = ImageConfigComplete & { allSizes: number[] } type ImageConfig = ImageConfigComplete & { allSizes: number[] }
export { ImageLoaderProps } export type { ImageLoaderProps }
export type ImageLoader = (p: ImageLoaderProps) => string export type ImageLoader = (p: ImageLoaderProps) => string
// Do not export - this is an internal type only // Do not export - this is an internal type only
......
module.exports = module.exports = require('./dist/client/script')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/client/script')
: require('./dist/client/script')
...@@ -2072,6 +2072,9 @@ describe('Prerender', () => { ...@@ -2072,6 +2072,9 @@ describe('Prerender', () => {
const { version, files } = JSON.parse(contents) const { version, files } = JSON.parse(contents)
expect(version).toBe(1) expect(version).toBe(1)
console.log(
check.tests.map((item) => files.some((file) => item.test(file)))
)
expect( expect(
check.tests.every((item) => files.some((file) => item.test(file))) check.tests.every((item) => files.some((file) => item.test(file)))
).toBe(true) ).toBe(true)
......
...@@ -65,6 +65,11 @@ describe('react 18 streaming SSR with custom next configs', () => { ...@@ -65,6 +65,11 @@ describe('react 18 streaming SSR with custom next configs', () => {
expect(html).toContain('home') expect(html).toContain('home')
}) })
it('should render next/router correctly in edge runtime', async () => {
const html = await renderViaHTTP(next.url, '/router')
expect(html).toContain('link')
})
it('should render multi-byte characters correctly in streaming', async () => { it('should render multi-byte characters correctly in streaming', async () => {
const html = await renderViaHTTP(next.url, '/multi-byte') const html = await renderViaHTTP(next.url, '/multi-byte')
expect(html).toContain('マルチバイト'.repeat(28)) expect(html).toContain('マルチバイト'.repeat(28))
......
import { useRouter } from 'next/router'
import Link from 'next/link'
export default () => {
useRouter()
return <Link href="/">link</Link>
}
export const config = {
runtime: 'experimental-edge',
}
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