Unverified Commit 9fcf39ac authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Refactor <Document> files (#16184)

Instead of reading the `BuildManifest` and passing it to `/_document`, it should be able to read it for itself.

---

Fixes #16182
parent db40a39f
...@@ -171,7 +171,6 @@ export type DocumentProps = DocumentInitialProps & { ...@@ -171,7 +171,6 @@ export type DocumentProps = DocumentInitialProps & {
inAmpMode: boolean inAmpMode: boolean
hybridAmp: boolean hybridAmp: boolean
isDevelopment: boolean isDevelopment: boolean
files: string[]
dynamicImports: ManifestItem[] dynamicImports: ManifestItem[]
assetPrefix?: string assetPrefix?: string
canonicalBase: string canonicalBase: string
......
...@@ -45,7 +45,6 @@ import { ...@@ -45,7 +45,6 @@ import {
import { tryGetPreviewData, __ApiPreviewProps } from './api-utils' import { tryGetPreviewData, __ApiPreviewProps } from './api-utils'
import { denormalizePagePath } from './denormalize-page-path' import { denormalizePagePath } from './denormalize-page-path'
import { FontManifest, getFontDefinitionFromManifest } from './font-utils' import { FontManifest, getFontDefinitionFromManifest } from './font-utils'
import { getPageFiles } from './get-page-files'
import { LoadComponentsReturnType, ManifestItem } from './load-components' import { LoadComponentsReturnType, ManifestItem } from './load-components'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
import optimizeAmp from './optimize-amp' import optimizeAmp from './optimize-amp'
...@@ -178,7 +177,6 @@ function renderDocument( ...@@ -178,7 +177,6 @@ function renderDocument(
ampState, ampState,
inAmpMode, inAmpMode,
hybridAmp, hybridAmp,
files,
dynamicImports, dynamicImports,
headTags, headTags,
gsp, gsp,
...@@ -200,7 +198,6 @@ function renderDocument( ...@@ -200,7 +198,6 @@ function renderDocument(
hybridAmp: boolean hybridAmp: boolean
dynamicImportsIds: string[] dynamicImportsIds: string[]
dynamicImports: ManifestItem[] dynamicImports: ManifestItem[]
files: string[]
headTags: any headTags: any
isFallback?: boolean isFallback?: boolean
gsp?: boolean gsp?: boolean
...@@ -242,7 +239,6 @@ function renderDocument( ...@@ -242,7 +239,6 @@ function renderDocument(
inAmpMode, inAmpMode,
isDevelopment: !!dev, isDevelopment: !!dev,
hybridAmp, hybridAmp,
files,
dynamicImports, dynamicImports,
assetPrefix, assetPrefix,
headTags, headTags,
...@@ -701,18 +697,6 @@ export async function renderToHTML( ...@@ -701,18 +697,6 @@ export async function renderToHTML(
} }
} }
// AMP First pages do not have client-side JavaScript files
const files = ampState.ampFirst
? []
: [
...new Set([
...getPageFiles(filteredBuildManifest, '/_app'),
...(pathname !== '/_error'
? getPageFiles(filteredBuildManifest, pathname)
: []),
]),
]
const renderPage: RenderPage = ( const renderPage: RenderPage = (
options: ComponentsEnhancer = {} options: ComponentsEnhancer = {}
): { html: string; head: any } => { ): { html: string; head: any } => {
...@@ -796,7 +780,6 @@ export async function renderToHTML( ...@@ -796,7 +780,6 @@ export async function renderToHTML(
hybridAmp, hybridAmp,
dynamicImportsIds, dynamicImportsIds,
dynamicImports, dynamicImports,
files,
gsp: !!getStaticProps ? true : undefined, gsp: !!getStaticProps ? true : undefined,
gssp: !!getServerSideProps ? true : undefined, gssp: !!getServerSideProps ? true : undefined,
gip: hasPageGetInitialProps ? true : undefined, gip: hasPageGetInitialProps ? true : undefined,
......
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import React, { useContext, Component, ReactNode } from 'react' import React, { Component, ReactNode, useContext } from 'react'
import flush from 'styled-jsx/server' import flush from 'styled-jsx/server'
import { import {
AMP_RENDER_TARGET, AMP_RENDER_TARGET,
...@@ -11,6 +11,10 @@ import { ...@@ -11,6 +11,10 @@ import {
DocumentInitialProps, DocumentInitialProps,
DocumentProps, DocumentProps,
} from '../next-server/lib/utils' } from '../next-server/lib/utils'
import {
BuildManifest,
getPageFiles,
} from '../next-server/server/get-page-files'
import { cleanAmpPath } from '../next-server/server/utils' import { cleanAmpPath } from '../next-server/server/utils'
import { htmlEscapeJsonString } from '../server/htmlescape' import { htmlEscapeJsonString } from '../server/htmlescape'
...@@ -40,6 +44,27 @@ function getOptionalModernScriptVariant(path: string): string { ...@@ -40,6 +44,27 @@ function getOptionalModernScriptVariant(path: string): string {
return path return path
} }
type DocumentFiles = {
sharedFiles: readonly string[]
pageFiles: readonly string[]
allFiles: readonly string[]
}
function getDocumentFiles(
buildManifest: BuildManifest,
pathname: string
): DocumentFiles {
const sharedFiles: readonly string[] = getPageFiles(buildManifest, '/_app')
const pageFiles: readonly string[] =
pathname !== '/_error' ? getPageFiles(buildManifest, pathname) : []
return {
sharedFiles,
pageFiles,
allFiles: [...new Set([...sharedFiles, ...pageFiles])],
}
}
/** /**
* `Document` component handles the initial `document` markup and renders only on the server side. * `Document` component handles the initial `document` markup and renders only on the server side.
* Commonly used for implementing server side rendering for `css-in-js` libraries. * Commonly used for implementing server side rendering for `css-in-js` libraries.
...@@ -126,10 +151,9 @@ export class Head extends Component< ...@@ -126,10 +151,9 @@ export class Head extends Component<
context!: React.ContextType<typeof DocumentComponentContext> context!: React.ContextType<typeof DocumentComponentContext>
getCssLinks(): JSX.Element[] | null { getCssLinks(files: DocumentFiles): JSX.Element[] | null {
const { assetPrefix, files, devOnlyCacheBusterQueryString } = this.context const { assetPrefix, devOnlyCacheBusterQueryString } = this.context
const cssFiles = const cssFiles = files.allFiles.filter((f) => f.endsWith('.css'))
files && files.length ? files.filter((f) => f.endsWith('.css')) : []
const cssLinkElements: JSX.Element[] = [] const cssLinkElements: JSX.Element[] = []
cssFiles.forEach((file) => { cssFiles.forEach((file) => {
...@@ -200,18 +224,14 @@ export class Head extends Component< ...@@ -200,18 +224,14 @@ export class Head extends Component<
) )
} }
getPreloadMainLinks(): JSX.Element[] | null { getPreloadMainLinks(files: DocumentFiles): JSX.Element[] | null {
const { assetPrefix, files, devOnlyCacheBusterQueryString } = this.context const { assetPrefix, devOnlyCacheBusterQueryString } = this.context
const preloadFiles = files.allFiles.filter((file: string) => {
const preloadFiles =
files && files.length
? files.filter((file: string) => {
// `dynamicImports` will contain both `.js` and `.module.js` when // `dynamicImports` will contain both `.js` and `.module.js` when
// the feature is enabled. This clause will filter down to the // the feature is enabled. This clause will filter down to the
// modern variants only. // modern variants only.
return file.endsWith(getOptionalModernScriptVariant('.js')) return file.endsWith(getOptionalModernScriptVariant('.js'))
}) })
: []
return !preloadFiles.length return !preloadFiles.length
? null ? null
...@@ -366,6 +386,10 @@ export class Head extends Component< ...@@ -366,6 +386,10 @@ export class Head extends Component<
}) })
} }
const files: DocumentFiles = getDocumentFiles(
this.context.buildManifest,
this.context.__NEXT_DATA__.page
)
return ( return (
<head {...this.props}> <head {...this.props}>
{this.context.isDevelopment && ( {this.context.isDevelopment && (
...@@ -452,10 +476,10 @@ export class Head extends Component< ...@@ -452,10 +476,10 @@ export class Head extends Component<
/> />
)} )}
{process.env.__NEXT_OPTIMIZE_FONTS {process.env.__NEXT_OPTIMIZE_FONTS
? this.makeStylesheetInert(this.getCssLinks()) ? this.makeStylesheetInert(this.getCssLinks(files))
: this.getCssLinks()} : this.getCssLinks(files)}
{!disableRuntimeJS && this.getPreloadDynamicChunks()} {!disableRuntimeJS && this.getPreloadDynamicChunks()}
{!disableRuntimeJS && this.getPreloadMainLinks()} {!disableRuntimeJS && this.getPreloadMainLinks(files)}
{this.context.isDevelopment && ( {this.context.isDevelopment && (
// this element is used to mount development styles so the // this element is used to mount development styles so the
// ordering matches production // ordering matches production
...@@ -491,11 +515,10 @@ export class NextScript extends Component<OriginProps> { ...@@ -491,11 +515,10 @@ export class NextScript extends Component<OriginProps> {
static safariNomoduleFix = static safariNomoduleFix =
'!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();' '!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();'
getDynamicChunks() { getDynamicChunks(files: DocumentFiles) {
const { const {
dynamicImports, dynamicImports,
assetPrefix, assetPrefix,
files,
isDevelopment, isDevelopment,
devOnlyCacheBusterQueryString, devOnlyCacheBusterQueryString,
} = this.context } = this.context
...@@ -508,7 +531,7 @@ export class NextScript extends Component<OriginProps> { ...@@ -508,7 +531,7 @@ export class NextScript extends Component<OriginProps> {
: { noModule: true } : { noModule: true }
} }
if (!bundle.file.endsWith('.js') || files.includes(bundle.file)) if (!bundle.file.endsWith('.js') || files.allFiles.includes(bundle.file))
return null return null
return ( return (
...@@ -528,16 +551,15 @@ export class NextScript extends Component<OriginProps> { ...@@ -528,16 +551,15 @@ export class NextScript extends Component<OriginProps> {
}) })
} }
getScripts() { getScripts(files: DocumentFiles) {
const { const {
assetPrefix, assetPrefix,
files,
buildManifest, buildManifest,
isDevelopment, isDevelopment,
devOnlyCacheBusterQueryString, devOnlyCacheBusterQueryString,
} = this.context } = this.context
const normalScripts = files?.filter((file) => file.endsWith('.js')) const normalScripts = files.allFiles.filter((file) => file.endsWith('.js'))
const lowPriorityScripts = buildManifest.lowPriorityFiles?.filter((file) => const lowPriorityScripts = buildManifest.lowPriorityFiles?.filter((file) =>
file.endsWith('.js') file.endsWith('.js')
) )
...@@ -667,6 +689,10 @@ export class NextScript extends Component<OriginProps> { ...@@ -667,6 +689,10 @@ export class NextScript extends Component<OriginProps> {
) )
} }
const files: DocumentFiles = getDocumentFiles(
this.context.buildManifest,
this.context.__NEXT_DATA__.page
)
return ( return (
<> <>
{!disableRuntimeJS && buildManifest.devFiles {!disableRuntimeJS && buildManifest.devFiles
...@@ -709,8 +735,8 @@ export class NextScript extends Component<OriginProps> { ...@@ -709,8 +735,8 @@ export class NextScript extends Component<OriginProps> {
/> />
) : null} ) : null}
{!disableRuntimeJS && this.getPolyfillScripts()} {!disableRuntimeJS && this.getPolyfillScripts()}
{disableRuntimeJS ? null : this.getDynamicChunks()} {disableRuntimeJS ? null : this.getDynamicChunks(files)}
{disableRuntimeJS ? null : this.getScripts()} {disableRuntimeJS ? null : this.getScripts(files)}
</> </>
) )
} }
......
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