From 28dc5a276c765d539cea270bd242dbe4342fa4f0 Mon Sep 17 00:00:00 2001 From: Tim Neutkens Date: Sun, 7 Jun 2020 01:00:03 +0200 Subject: [PATCH] Clean up render.tsx options (#13759) Went through and removed a bunch of internal options which are just pass-through values of buildManifest Closes #13851 --- .../next/build/plugins/collect-plugins.ts | 2 - packages/next/build/webpack-config.ts | 2 +- .../webpack/plugins/build-manifest-plugin.ts | 3 +- .../webpack/plugins/react-loadable-plugin.ts | 16 +- packages/next/client/page-loader.js | 4 +- packages/next/export/index.ts | 1 - packages/next/next-server/lib/utils.ts | 8 +- .../next/next-server/server/get-page-files.ts | 1 + .../next-server/server/load-components.ts | 1 - .../next/next-server/server/next-server.ts | 4 - packages/next/next-server/server/render.tsx | 45 +----- packages/next/pages/_document.tsx | 145 +++++++++--------- packages/next/server/next.ts | 2 +- .../client-navigation/test/rendering.js | 3 +- .../src/document-body-tags-server.js | 7 - .../src/document-html-props-server.js | 5 - .../next-plugins/test/index.test.js | 18 --- .../integration/production/test/index.test.js | 2 +- 18 files changed, 91 insertions(+), 178 deletions(-) delete mode 100644 test/integration/next-plugins/app/node_modules/@next/plugin-google-analytics/src/document-body-tags-server.js delete mode 100644 test/integration/next-plugins/app/node_modules/@next/plugin-google-analytics/src/document-html-props-server.js diff --git a/packages/next/build/plugins/collect-plugins.ts b/packages/next/build/plugins/collect-plugins.ts index 3c46aa8c16cbe1..e0d80e3951eeb1 100644 --- a/packages/next/build/plugins/collect-plugins.ts +++ b/packages/next/build/plugins/collect-plugins.ts @@ -17,8 +17,6 @@ export type PluginMetaData = { // currently supported middleware export const VALID_MIDDLEWARE = [ 'document-head-tags-server', - 'document-body-tags-server', - 'document-html-props-server', 'on-init-client', 'on-init-server', 'on-error-server', diff --git a/packages/next/build/webpack-config.ts b/packages/next/build/webpack-config.ts index 23dbae7c485e8f..6b97311ef164f4 100644 --- a/packages/next/build/webpack-config.ts +++ b/packages/next/build/webpack-config.ts @@ -803,7 +803,7 @@ export default async function getBaseWebpackConfig( } }, {}), 'process.env.NODE_ENV': JSON.stringify(webpackMode), - 'process.crossOrigin': JSON.stringify(crossOrigin), + 'process.env.__NEXT_CROSS_ORIGIN': JSON.stringify(crossOrigin), 'process.browser': JSON.stringify(!isServer), 'process.env.__NEXT_TEST_MODE': JSON.stringify( process.env.__NEXT_TEST_MODE diff --git a/packages/next/build/webpack/plugins/build-manifest-plugin.ts b/packages/next/build/webpack/plugins/build-manifest-plugin.ts index 64d7fdbf4b34db..ef1b9bbb1f2fc3 100644 --- a/packages/next/build/webpack/plugins/build-manifest-plugin.ts +++ b/packages/next/build/webpack/plugins/build-manifest-plugin.ts @@ -56,6 +56,7 @@ export default class BuildManifestPlugin { (compilation, callback) => { const { chunks } = compilation const assetMap: BuildManifest = { + polyfillFiles: [], devFiles: [], lowPriorityFiles: [], pages: { '/_app': [] }, @@ -115,7 +116,7 @@ export default class BuildManifestPlugin { } // Create a separate entry for polyfills - assetMap.pages['/_polyfills'] = polyfillFiles + assetMap.polyfillFiles = polyfillFiles // Add the runtime build manifest file (generated later in this file) // as a dependency for the app. If the flag is false, the file won't be diff --git a/packages/next/build/webpack/plugins/react-loadable-plugin.ts b/packages/next/build/webpack/plugins/react-loadable-plugin.ts index ab418acadba6cb..afd16f1fe63d3c 100644 --- a/packages/next/build/webpack/plugins/react-loadable-plugin.ts +++ b/packages/next/build/webpack/plugins/react-loadable-plugin.ts @@ -21,8 +21,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR // Implementation of this PR: https://github.com/jamiebuilds/react-loadable/pull/132 // Modified to strip out unneeded results for Next's specific use case -import url from 'url' - import { Compiler, // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -30,10 +28,9 @@ import { } from 'webpack' function buildManifest( - compiler: Compiler, + _compiler: Compiler, compilation: CompilationType.Compilation ) { - let context = compiler.options.context let manifest: { [k: string]: any[] } = {} compilation.chunkGroups.forEach((chunkGroup) => { @@ -50,17 +47,8 @@ function buildManifest( return } - let publicPath = url.resolve( - compilation.outputOptions.publicPath || '', - file - ) - for (const module of chunk.modulesIterable) { let id = module.id - let name = - typeof module.libIdent === 'function' - ? module.libIdent({ context }) - : null if (!manifest[request]) { manifest[request] = [] @@ -77,9 +65,7 @@ function buildManifest( manifest[request].push({ id, - name, file, - publicPath, }) } }) diff --git a/packages/next/client/page-loader.js b/packages/next/client/page-loader.js index 5119b553876293..de4ff15e9d0f43 100644 --- a/packages/next/client/page-loader.js +++ b/packages/next/client/page-loader.js @@ -44,7 +44,7 @@ export function getAssetPath(route) { function appendLink(href, rel, as) { return new Promise((res, rej, link) => { link = document.createElement('link') - link.crossOrigin = process.crossOrigin + link.crossOrigin = process.env.__NEXT_CROSS_ORIGIN link.href = href link.rel = rel if (as) link.as = as @@ -267,7 +267,7 @@ export default class PageLoader { // dependencies already have it added during build manifest creation if (isPage) url = url.replace(/\.js$/, '.module.js') } - script.crossOrigin = process.crossOrigin + script.crossOrigin = process.env.__NEXT_CROSS_ORIGIN script.src = url script.onerror = () => { const error = new Error(`Error loading script ${url}`) diff --git a/packages/next/export/index.ts b/packages/next/export/index.ts index a9ae960b7c4351..8961a3ea7a96a3 100644 --- a/packages/next/export/index.ts +++ b/packages/next/export/index.ts @@ -251,7 +251,6 @@ export default async function exportApp( assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''), distDir, dev: false, - staticMarkup: false, hotReloader: null, basePath: nextConfig.experimental.basePath, canonicalBase: nextConfig.amp?.canonicalBase || '', diff --git a/packages/next/next-server/lib/utils.ts b/packages/next/next-server/lib/utils.ts index 87dbfa0772b6a5..4b255709eb9662 100644 --- a/packages/next/next-server/lib/utils.ts +++ b/packages/next/next-server/lib/utils.ts @@ -5,6 +5,7 @@ import { format, URLFormatOptions, UrlObject } from 'url' import { ManifestItem } from '../server/load-components' import { NextRouter } from './router/router' import { Env } from '../../lib/load-env-config' +import { BuildManifest } from '../server/get-page-files' /** * Types used by both next and next-server @@ -153,20 +154,15 @@ export type DocumentInitialProps = RenderPageResult & { export type DocumentProps = DocumentInitialProps & { __NEXT_DATA__: NEXT_DATA dangerousAsPath: string + buildManifest: BuildManifest ampPath: string inAmpMode: boolean hybridAmp: boolean - staticMarkup: boolean isDevelopment: boolean - devFiles: string[] files: string[] - lowPriorityFiles: string[] - polyfillFiles: string[] dynamicImports: ManifestItem[] assetPrefix?: string canonicalBase: string - htmlProps: any - bodyTags: any[] headTags: any[] unstable_runtimeJS?: false } diff --git a/packages/next/next-server/server/get-page-files.ts b/packages/next/next-server/server/get-page-files.ts index c42b5a0f25e8a0..3adafe2edf8dc0 100644 --- a/packages/next/next-server/server/get-page-files.ts +++ b/packages/next/next-server/server/get-page-files.ts @@ -2,6 +2,7 @@ import { normalizePagePath, denormalizePagePath } from './normalize-page-path' export type BuildManifest = { devFiles: string[] + polyfillFiles: string[] lowPriorityFiles: string[] pages: { '/_app': string[] diff --git a/packages/next/next-server/server/load-components.ts b/packages/next/next-server/server/load-components.ts index e67aa0d699e027..de09e852e5dc8b 100644 --- a/packages/next/next-server/server/load-components.ts +++ b/packages/next/next-server/server/load-components.ts @@ -23,7 +23,6 @@ export type ManifestItem = { id: number | string name: string file: string - publicPath: string } type ReactLoadableManifest = { [moduleId: string]: ManifestItem[] } diff --git a/packages/next/next-server/server/next-server.ts b/packages/next/next-server/server/next-server.ts index 88918507fce9dd..babd4aa96b94e2 100644 --- a/packages/next/next-server/server/next-server.ts +++ b/packages/next/next-server/server/next-server.ts @@ -87,7 +87,6 @@ export type ServerConstructor = { * Where the Next project is located - @default '.' */ dir?: string - staticMarkup?: boolean /** * Hide error messages containing server information - @default false */ @@ -113,7 +112,6 @@ export default class Server { buildId: string renderOpts: { poweredByHeader: boolean - staticMarkup: boolean buildId: string generateEtags: boolean runtimeConfig?: { [key: string]: any } @@ -140,7 +138,6 @@ export default class Server { public constructor({ dir = '.', - staticMarkup = false, quiet = false, conf = null, dev = false, @@ -171,7 +168,6 @@ export default class Server { this.renderOpts = { poweredByHeader: this.nextConfig.poweredByHeader, canonicalBase: this.nextConfig.amp.canonicalBase, - staticMarkup, buildId: this.buildId, generateEtags, previewProps: this.getPreviewProps(), diff --git a/packages/next/next-server/server/render.tsx b/packages/next/next-server/server/render.tsx index b1d5de9a1b727b..e0c7329c9ab1c3 100644 --- a/packages/next/next-server/server/render.tsx +++ b/packages/next/next-server/server/render.tsx @@ -119,7 +119,6 @@ function enhanceComponents( } function render( - renderElementToString: (element: React.ReactElement) => string, element: React.ReactElement, ampMode: any ): { html: string; head: React.ReactElement[] } { @@ -127,7 +126,7 @@ function render( let head try { - html = renderElementToString(element) + html = renderToString(element) } finally { head = Head.rewind() || defaultHead(isInAmpMode(ampMode)) } @@ -136,7 +135,6 @@ function render( } export type RenderOptsPartial = { - staticMarkup: boolean buildId: string canonicalBase: string runtimeConfig?: { [key: string]: any } @@ -165,6 +163,7 @@ export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial function renderDocument( Document: DocumentType, { + buildManifest, props, docProps, pathname, @@ -184,14 +183,8 @@ function renderDocument( ampState, inAmpMode, hybridAmp, - staticMarkup, - devFiles, files, - lowPriorityFiles, - polyfillFiles, dynamicImports, - htmlProps, - bodyTags, headTags, gsp, gssp, @@ -211,12 +204,7 @@ function renderDocument( hybridAmp: boolean dynamicImportsIds: string[] dynamicImports: ManifestItem[] - devFiles: string[] files: string[] - lowPriorityFiles: string[] - polyfillFiles: string[] - htmlProps: any - bodyTags: any headTags: any isFallback?: boolean gsp?: boolean @@ -250,21 +238,16 @@ function renderDocument( gip, // whether the page has getInitialProps appGip, // whether the _app has getInitialProps }, + buildManifest, dangerousAsPath, canonicalBase, ampPath, inAmpMode, isDevelopment: !!dev, hybridAmp, - staticMarkup, - devFiles, files, - lowPriorityFiles, - polyfillFiles, dynamicImports, assetPrefix, - htmlProps, - bodyTags, headTags, unstable_runtimeJS, ...docProps, @@ -293,7 +276,6 @@ export async function renderToHTML( const { err, dev = false, - staticMarkup = false, ampPath = '', App, Document, @@ -334,8 +316,6 @@ export async function renderToHTML( } const headTags = (...args: any) => callMiddleware('headTags', args) - const bodyTags = (...args: any) => callMiddleware('bodyTags', args) - const htmlProps = (...args: any) => callMiddleware('htmlProps', args, true) const didRewrite = (req as any)._nextDidRewrite const isFallback = !!query.__nextFallback @@ -674,27 +654,16 @@ export async function renderToHTML( // the response might be finished on the getInitialProps call if (isResSent(res) && !isSSG) return null - const devFiles = buildManifest.devFiles const files = [ ...new Set([ ...getPageFiles(buildManifest, '/_app'), ...getPageFiles(buildManifest, pathname), ]), ] - const lowPriorityFiles = buildManifest.lowPriorityFiles - const polyfillFiles = getPageFiles(buildManifest, '/_polyfills') - - const renderElementToString = staticMarkup - ? renderToStaticMarkup - : renderToString const renderPageError = (): { html: string; head: any } | void => { if (ctx.err && ErrorDebug) { - return render( - renderElementToString, - , - ampState - ) + return render(, ampState) } if (dev && (props.router || props.Component)) { @@ -716,7 +685,6 @@ export async function renderToHTML( } = enhanceComponents(options, App, Component) return render( - renderElementToString, , @@ -771,8 +739,6 @@ export async function renderToHTML( ampState, props, headTags: await headTags(documentCtx), - bodyTags: await bodyTags(documentCtx), - htmlProps: await htmlProps(documentCtx), isFallback, docProps, pathname, @@ -782,10 +748,7 @@ export async function renderToHTML( hybridAmp, dynamicImportsIds, dynamicImports, - devFiles, files, - lowPriorityFiles, - polyfillFiles, gsp: !!getStaticProps ? true : undefined, gssp: !!getServerSideProps ? true : undefined, gip: hasPageGetInitialProps ? true : undefined, diff --git a/packages/next/pages/_document.tsx b/packages/next/pages/_document.tsx index 1b967bacd156b8..55e49645aaf3d2 100644 --- a/packages/next/pages/_document.tsx +++ b/packages/next/pages/_document.tsx @@ -1,5 +1,5 @@ import PropTypes from 'prop-types' -import React, { Component } from 'react' +import React, { useContext, Component } from 'react' import flush from 'styled-jsx/server' import { AMP_RENDER_TARGET, @@ -53,18 +53,6 @@ export default class Document

extends Component { 'next-plugin-loader?middleware=document-head-tags-server!' ) : () => [] - static bodyTagsMiddleware = process.env.__NEXT_PLUGINS - ? import( - // @ts-ignore loader syntax - 'next-plugin-loader?middleware=document-body-tags-server!' - ) - : () => [] - static htmlPropsMiddleware = process.env.__NEXT_PLUGINS - ? import( - // @ts-ignore loader syntax - 'next-plugin-loader?middleware=document-html-props-server!' - ) - : () => [] /** * `getInitialProps` hook returns the context object with the addition of `renderPage`. @@ -133,33 +121,22 @@ export default class Document

extends Component { } } -export class Html extends Component< - React.DetailedHTMLProps< +export function Html( + props: React.DetailedHTMLProps< React.HtmlHTMLAttributes, HTMLHtmlElement > -> { - static contextType = DocumentComponentContext - - static propTypes = { - children: PropTypes.node.isRequired, - } - - context!: React.ContextType - - render() { - const { inAmpMode, htmlProps } = this.context._documentProps - return ( - - ) - } +) { + const { inAmpMode } = useContext(DocumentComponentContext)._documentProps + return ( + + ) } export class Head extends Component< @@ -195,7 +172,9 @@ export class Head extends Component< file )}${_devOnlyInvalidateCacheQueryString}`} as="style" - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } />, ) }) @@ -235,7 +216,9 @@ export class Head extends Component< )}${_devOnlyInvalidateCacheQueryString}`} as="script" nonce={this.props.nonce} - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } /> ) }) @@ -269,7 +252,9 @@ export class Head extends Component< file )}${_devOnlyInvalidateCacheQueryString}`} as="script" - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } /> )) } @@ -480,7 +465,9 @@ export class Head extends Component< } as="script" nonce={this.props.nonce} - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } /> )} {!disableRuntimeJS && page !== '/_error' && ( @@ -497,7 +484,9 @@ export class Head extends Component< } as="script" nonce={this.props.nonce} - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } /> )} {!disableRuntimeJS && this.getPreloadDynamicChunks()} @@ -565,7 +554,9 @@ export class NextScript extends Component { bundle.file )}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } {...modernProps} /> ) @@ -573,11 +564,11 @@ export class NextScript extends Component { } getScripts() { - const { assetPrefix, files, lowPriorityFiles } = this.context._documentProps + const { assetPrefix, files, buildManifest } = this.context._documentProps const { _devOnlyInvalidateCacheQueryString } = this.context const normalScripts = files?.filter((file) => file.endsWith('.js')) - const lowPriorityScripts = lowPriorityFiles?.filter((file) => + const lowPriorityScripts = buildManifest.lowPriorityFiles?.filter((file) => file.endsWith('.js') ) @@ -596,7 +587,9 @@ export class NextScript extends Component { )}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} async - crossOrigin={this.props.crossOrigin || process.crossOrigin} + crossOrigin={ + this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN + } {...modernProps} /> ) @@ -606,10 +599,10 @@ export class NextScript extends Component { getPolyfillScripts() { // polyfills.js has to be rendered as nomodule without async // It also has to be the first script to load - const { assetPrefix, polyfillFiles } = this.context._documentProps + const { assetPrefix, buildManifest } = this.context._documentProps const { _devOnlyInvalidateCacheQueryString } = this.context - return polyfillFiles + return buildManifest.polyfillFiles .filter( (polyfill) => polyfill.endsWith('.js') && !/\.module\.js$/.test(polyfill) @@ -618,7 +611,9 @@ export class NextScript extends Component {