Unverified Commit df77964e authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Preload chunks for next/dynamic in suspense mode (#37245)

When using `next/dynamic` with `suspense: true`, the API will opt into `React.lazy` with react 18. But previously it doesn't preload the dynamic chunks. This pr will include the chunks into initial html for faster hydration instead of loading the chunk until the script is executed. This makes `next/dynamic` has a significant difference from `React.lazy` api

x-ref: https://github.com/vercel/next.js/issues/37197#issuecomment-1138496911
x-ref: https://github.com/vercel/next.js/pull/37244
parent 3e178bb8
...@@ -16,7 +16,7 @@ export type LoadableGeneratedOptions = { ...@@ -16,7 +16,7 @@ export type LoadableGeneratedOptions = {
modules?(): LoaderMap modules?(): LoaderMap
} }
export type LoadableBaseOptions<P = {}> = LoadableGeneratedOptions & { export type DynamicOptions<P = {}> = LoadableGeneratedOptions & {
loading?: ({ loading?: ({
error, error,
isLoading, isLoading,
...@@ -31,27 +31,20 @@ export type LoadableBaseOptions<P = {}> = LoadableGeneratedOptions & { ...@@ -31,27 +31,20 @@ export type LoadableBaseOptions<P = {}> = LoadableGeneratedOptions & {
loader?: Loader<P> | LoaderMap loader?: Loader<P> | LoaderMap
loadableGenerated?: LoadableGeneratedOptions loadableGenerated?: LoadableGeneratedOptions
ssr?: boolean ssr?: boolean
}
export type LoadableSuspenseOptions = {
suspense?: boolean suspense?: boolean
} }
export type LoadableOptions<P = {}> = LoadableBaseOptions<P> export type LoadableOptions<P = {}> = DynamicOptions<P>
export type DynamicOptions<P = {}> =
| LoadableBaseOptions<P>
| LoadableSuspenseOptions
export type LoadableFn<P = {}> = ( export type LoadableFn<P = {}> = (
opts: LoadableOptions<P> | LoadableSuspenseOptions opts: LoadableOptions<P>
) => React.ComponentType<P> ) => React.ComponentType<P>
export type LoadableComponent<P = {}> = React.ComponentType<P> export type LoadableComponent<P = {}> = React.ComponentType<P>
export function noSSR<P = {}>( export function noSSR<P = {}>(
LoadableInitializer: LoadableFn<P>, LoadableInitializer: LoadableFn<P>,
loadableOptions: LoadableBaseOptions<P> loadableOptions: DynamicOptions<P>
): React.ComponentType<P> { ): React.ComponentType<P> {
// Removing webpack and modules means react-loadable won't try preloading // Removing webpack and modules means react-loadable won't try preloading
delete loadableOptions.webpack delete loadableOptions.webpack
...@@ -114,18 +107,12 @@ export default function dynamic<P = {}>( ...@@ -114,18 +107,12 @@ export default function dynamic<P = {}>(
// Support for passing options, eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>}) // Support for passing options, eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>})
loadableOptions = { ...loadableOptions, ...options } loadableOptions = { ...loadableOptions, ...options }
const suspenseOptions = loadableOptions as LoadableSuspenseOptions & {
loader: Loader<P>
}
// Error if Fizz rendering is not enabled and `suspense` option is set to true // Error if Fizz rendering is not enabled and `suspense` option is set to true
if (!process.env.__NEXT_REACT_ROOT && suspenseOptions.suspense) { if (!process.env.__NEXT_REACT_ROOT && loadableOptions.suspense) {
throw new Error( throw new Error(
`Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense` `Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense`
) )
} }
if (suspenseOptions.suspense) {
return loadableFn(suspenseOptions)
}
// coming from build/babel/plugins/react-loadable-plugin.js // coming from build/babel/plugins/react-loadable-plugin.js
if (loadableOptions.loadableGenerated) { if (loadableOptions.loadableGenerated) {
...@@ -136,8 +123,9 @@ export default function dynamic<P = {}>( ...@@ -136,8 +123,9 @@ export default function dynamic<P = {}>(
delete loadableOptions.loadableGenerated delete loadableOptions.loadableGenerated
} }
// support for disabling server side rendering, eg: dynamic(import('../hello-world'), {ssr: false}) // support for disabling server side rendering, eg: dynamic(import('../hello-world'), {ssr: false}).
if (typeof loadableOptions.ssr === 'boolean') { // skip `ssr` for suspense mode and opt-in React.lazy directly
if (typeof loadableOptions.ssr === 'boolean' && !loadableOptions.suspense) {
if (!loadableOptions.ssr) { if (!loadableOptions.ssr) {
delete loadableOptions.ssr delete loadableOptions.ssr
return noSSR(loadableFn, loadableOptions) return noSSR(loadableFn, loadableOptions)
......
...@@ -94,12 +94,12 @@ function createLoadableComponent(loadFn, options) { ...@@ -94,12 +94,12 @@ function createLoadableComponent(loadFn, options) {
} }
// Server only // Server only
if (typeof window === 'undefined' && !opts.suspense) { if (typeof window === 'undefined') {
ALL_INITIALIZERS.push(init) ALL_INITIALIZERS.push(init)
} }
// Client only // Client only
if (!initialized && typeof window !== 'undefined' && !opts.suspense) { if (!initialized && typeof window !== 'undefined') {
// require.resolveWeak check is needed for environments that don't have it available like Jest // require.resolveWeak check is needed for environments that don't have it available like Jest
const moduleIds = const moduleIds =
opts.webpack && typeof require.resolveWeak === 'function' opts.webpack && typeof require.resolveWeak === 'function'
...@@ -116,10 +116,20 @@ function createLoadableComponent(loadFn, options) { ...@@ -116,10 +116,20 @@ function createLoadableComponent(loadFn, options) {
} }
} }
function LoadableImpl(props, ref) { function useLoadableModule() {
init() init()
const context = React.useContext(LoadableContext) const context = React.useContext(LoadableContext)
if (context && Array.isArray(opts.modules)) {
opts.modules.forEach((moduleName) => {
context(moduleName)
})
}
}
function LoadableImpl(props, ref) {
useLoadableModule()
const state = useSyncExternalStore( const state = useSyncExternalStore(
subscription.subscribe, subscription.subscribe,
subscription.getCurrentValue, subscription.getCurrentValue,
...@@ -134,12 +144,6 @@ function createLoadableComponent(loadFn, options) { ...@@ -134,12 +144,6 @@ function createLoadableComponent(loadFn, options) {
[] []
) )
if (context && Array.isArray(opts.modules)) {
opts.modules.forEach((moduleName) => {
context(moduleName)
})
}
return React.useMemo(() => { return React.useMemo(() => {
if (state.loading || state.error) { if (state.loading || state.error) {
return React.createElement(opts.loading, { return React.createElement(opts.loading, {
...@@ -158,11 +162,13 @@ function createLoadableComponent(loadFn, options) { ...@@ -158,11 +162,13 @@ function createLoadableComponent(loadFn, options) {
} }
function LazyImpl(props, ref) { function LazyImpl(props, ref) {
useLoadableModule()
return React.createElement(opts.lazy, { ...props, ref }) return React.createElement(opts.lazy, { ...props, ref })
} }
const LoadableComponent = opts.suspense ? LazyImpl : LoadableImpl const LoadableComponent = opts.suspense ? LazyImpl : LoadableImpl
LoadableComponent.preload = () => !opts.suspense && init() LoadableComponent.preload = () => init()
LoadableComponent.displayName = 'LoadableComponent' LoadableComponent.displayName = 'LoadableComponent'
return React.forwardRef(LoadableComponent) return React.forwardRef(LoadableComponent)
......
import dynamic from 'next/dynamic'
import { Suspense } from 'react'
const Foo = dynamic(() => import('../components/foo'), { suspense: true })
export default () => (
<div>
<Suspense fallback="fallback">
<Foo />
</Suspense>
</div>
)
...@@ -33,15 +33,19 @@ export default (context, env) => { ...@@ -33,15 +33,19 @@ export default (context, env) => {
expect(ssrId).toEqual(csrId) expect(ssrId).toEqual(csrId)
}) })
it('should contain dynamicIds in next data for basic dynamic imports', async () => { it('should contain dynamicIds in next data for dynamic imports', async () => {
const html = await renderViaHTTP(context.appPort, '/dynamic-imports') async function expectToContainPreload(page) {
const $ = cheerio.load(html) const html = await renderViaHTTP(context.appPort, `/${page}`)
const { dynamicIds } = JSON.parse($('#__NEXT_DATA__').html()) const $ = cheerio.load(html)
const { dynamicIds } = JSON.parse($('#__NEXT_DATA__').html())
if (env === 'dev') {
expect(dynamicIds).toContain('dynamic-imports.js -> ../components/foo') if (env === 'dev') {
} else { expect(dynamicIds).toContain(`${page}.js -> ../components/foo`)
expect(dynamicIds.length).toBe(1) } else {
expect(dynamicIds.length).toBe(1)
}
} }
await expectToContainPreload('dynamic')
await expectToContainPreload('dynamic-suspense')
}) })
} }
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