Unverified Commit b1848946 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Make sure polyfills are added for browsers without module support (#41029)

This PR makes sure that the same polyfills are added in app dir for
browsers that match `nomodule`. Main difference from the polyfills in
pages is that the script tags here cannot have `defer` as all other
scripts will be async by default, and polyfills must be executed before
all of them.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 2af441cf
...@@ -17,17 +17,10 @@ export class SubresourceIntegrityPlugin { ...@@ -17,17 +17,10 @@ export class SubresourceIntegrityPlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, },
(assets) => { (assets) => {
// Collect all the entrypoint files. // Collect all the assets.
let files = new Set<string>() let files = new Set<string>()
for (const entrypoint of compilation.entrypoints.values()) { for (const asset of compilation.getAssets()) {
const iterator = entrypoint?.getFiles() files.add(asset.name)
if (!iterator) {
continue
}
for (const file of iterator) {
files.add(file)
}
} }
// For each file, deduped, calculate the file hash. // For each file, deduped, calculate the file hash.
......
...@@ -1287,6 +1287,16 @@ export async function renderToHTMLOrFlight( ...@@ -1287,6 +1287,16 @@ export async function renderToHTMLOrFlight(
return flushed return flushed
} }
const polyfills = buildManifest.polyfillFiles
.filter(
(polyfill) =>
polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')
)
.map((polyfill) => ({
src: `${renderOpts.assetPrefix || ''}/_next/${polyfill}`,
integrity: subresourceIntegrityManifest?.[polyfill],
}))
try { try {
const renderStream = await renderToInitialStream({ const renderStream = await renderToInitialStream({
ReactDOMServer, ReactDOMServer,
...@@ -1295,14 +1305,16 @@ export async function renderToHTMLOrFlight( ...@@ -1295,14 +1305,16 @@ export async function renderToHTMLOrFlight(
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
nonce, nonce,
// Include hydration scripts in the HTML // Include hydration scripts in the HTML
bootstrapScripts: subresourceIntegrityManifest bootstrapScripts: [
? buildManifest.rootMainFiles.map((src) => ({ ...(subresourceIntegrityManifest
src: `${renderOpts.assetPrefix || ''}/_next/` + src, ? buildManifest.rootMainFiles.map((src) => ({
integrity: subresourceIntegrityManifest[src], src: `${renderOpts.assetPrefix || ''}/_next/` + src,
})) integrity: subresourceIntegrityManifest[src],
: buildManifest.rootMainFiles.map( }))
(src) => `${renderOpts.assetPrefix || ''}/_next/` + src : buildManifest.rootMainFiles.map(
), (src) => `${renderOpts.assetPrefix || ''}/_next/` + src
)),
],
}, },
}) })
...@@ -1311,6 +1323,7 @@ export async function renderToHTMLOrFlight( ...@@ -1311,6 +1323,7 @@ export async function renderToHTMLOrFlight(
generateStaticHTML: generateStaticHTML, generateStaticHTML: generateStaticHTML,
flushEffectHandler, flushEffectHandler,
flushEffectsToHead: true, flushEffectsToHead: true,
polyfills,
}) })
} catch (err: any) { } catch (err: any) {
// TODO-APP: show error overlay in development. `element` should probably be wrapped in AppRouter for this case. // TODO-APP: show error overlay in development. `element` should probably be wrapped in AppRouter for this case.
...@@ -1341,6 +1354,7 @@ export async function renderToHTMLOrFlight( ...@@ -1341,6 +1354,7 @@ export async function renderToHTMLOrFlight(
generateStaticHTML: generateStaticHTML, generateStaticHTML: generateStaticHTML,
flushEffectHandler, flushEffectHandler,
flushEffectsToHead: true, flushEffectsToHead: true,
polyfills,
}) })
} }
} }
......
...@@ -265,12 +265,14 @@ export async function continueFromInitialStream( ...@@ -265,12 +265,14 @@ export async function continueFromInitialStream(
generateStaticHTML, generateStaticHTML,
flushEffectHandler, flushEffectHandler,
flushEffectsToHead, flushEffectsToHead,
polyfills,
}: { }: {
suffix?: string suffix?: string
dataStream?: ReadableStream<Uint8Array> dataStream?: ReadableStream<Uint8Array>
generateStaticHTML: boolean generateStaticHTML: boolean
flushEffectHandler?: () => Promise<string> flushEffectHandler?: () => Promise<string>
flushEffectsToHead: boolean flushEffectsToHead: boolean
polyfills?: { src: string; integrity: string | undefined }[]
} }
): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
const closeTag = '</body></html>' const closeTag = '</body></html>'
...@@ -289,13 +291,26 @@ export async function continueFromInitialStream( ...@@ -289,13 +291,26 @@ export async function continueFromInitialStream(
dataStream ? createInlineDataStream(dataStream) : null, dataStream ? createInlineDataStream(dataStream) : null,
suffixUnclosed != null ? createSuffixStream(closeTag) : null, suffixUnclosed != null ? createSuffixStream(closeTag) : null,
createHeadInjectionTransformStream(async () => { createHeadInjectionTransformStream(async () => {
// Inject polyfills for browsers that don't support modules. It has to be
// blocking here and can't be `defer` because other scripts have `async`.
const polyfillScripts = polyfills
? polyfills
.map(
({ src, integrity }) =>
`<script src="${src}" nomodule=""${
integrity ? ` integrity="${integrity}"` : ''
}></script>`
)
.join('')
: ''
// TODO-APP: Inject flush effects to end of head in app layout rendering, to avoid // TODO-APP: Inject flush effects to end of head in app layout rendering, to avoid
// hydration errors. Remove this once it's ready to be handled by react itself. // hydration errors. Remove this once it's ready to be handled by react itself.
const flushEffectsContent = const flushEffectsContent =
flushEffectHandler && flushEffectsToHead flushEffectHandler && flushEffectsToHead
? await flushEffectHandler() ? await flushEffectHandler()
: '' : ''
return flushEffectsContent return polyfillScripts + flushEffectsContent
}), }),
].filter(nonNullable) ].filter(nonNullable)
......
...@@ -99,6 +99,13 @@ describe('app dir', () => { ...@@ -99,6 +99,13 @@ describe('app dir', () => {
expect(html).toContain('hello from dynamic on client') expect(html).toContain('hello from dynamic on client')
}) })
it('should serve polyfills for browsers that do not support modules', async () => {
const html = await renderViaHTTP(next.url, '/dashboard/index')
expect(html).toMatch(
/<script src="\/_next\/static\/chunks\/polyfills(-\w+)?\.js" nomodule="">/
)
})
// TODO-APP: handle css modules fouc in dev // TODO-APP: handle css modules fouc in dev
it.skip('should handle css imports in next/dynamic correctly', async () => { it.skip('should handle css imports in next/dynamic correctly', async () => {
const browser = await webdriver(next.url, '/dashboard/index') const browser = await webdriver(next.url, '/dashboard/index')
......
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