Unverified Commit 06d8acdf authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Update stylesheets on page navigation (#16126)

This pull request adds a test case for the reproduction provided in #12445. This bug is specifically caused when loading the next page before navigation has actually occurred.

---

Fixes #12445
parent cdff5dfb
...@@ -17,7 +17,7 @@ import * as envConfig from '../next-server/lib/runtime-config' ...@@ -17,7 +17,7 @@ import * as envConfig from '../next-server/lib/runtime-config'
import { getURL, loadGetInitialProps, ST } from '../next-server/lib/utils' import { getURL, loadGetInitialProps, ST } from '../next-server/lib/utils'
import type { NEXT_DATA } from '../next-server/lib/utils' import type { NEXT_DATA } from '../next-server/lib/utils'
import initHeadManager from './head-manager' import initHeadManager from './head-manager'
import PageLoader from './page-loader' import PageLoader, { createLink } from './page-loader'
import measureWebVitals from './performance-relayer' import measureWebVitals from './performance-relayer'
import { createRouter, makePublicRouterInstance } from './router' import { createRouter, makePublicRouterInstance } from './router'
...@@ -39,7 +39,7 @@ declare global { ...@@ -39,7 +39,7 @@ declare global {
} }
type RenderRouteInfo = PrivateRouteInfo & { App: AppComponent } type RenderRouteInfo = PrivateRouteInfo & { App: AppComponent }
type RenderErrorProps = Omit<RenderRouteInfo, 'Component'> type RenderErrorProps = Omit<RenderRouteInfo, 'Component' | 'styleSheets'>
if (!('finally' in Promise.prototype)) { if (!('finally' in Promise.prototype)) {
;(Promise.prototype as PromiseConstructor['prototype']).finally = require('next/dist/build/polyfills/finally-polyfill.min') ;(Promise.prototype as PromiseConstructor['prototype']).finally = require('next/dist/build/polyfills/finally-polyfill.min')
...@@ -84,7 +84,14 @@ if (hasBasePath(asPath)) { ...@@ -84,7 +84,14 @@ if (hasBasePath(asPath)) {
type RegisterFn = (input: [string, () => void]) => void type RegisterFn = (input: [string, () => void]) => void
const pageLoader = new PageLoader(buildId, prefix, page) const pageLoader = new PageLoader(
buildId,
prefix,
page,
[].slice
.call(document.querySelectorAll('link[rel=stylesheet][data-n-p]'))
.map((e: HTMLLinkElement) => e.getAttribute('href')!)
)
const register: RegisterFn = ([r, f]) => pageLoader.registerPage(r, f) const register: RegisterFn = ([r, f]) => pageLoader.registerPage(r, f)
if (window.__NEXT_P) { if (window.__NEXT_P) {
// Defer page registration for another tick. This will increase the overall // Defer page registration for another tick. This will increase the overall
...@@ -102,6 +109,7 @@ let lastRenderReject: (() => void) | null ...@@ -102,6 +109,7 @@ let lastRenderReject: (() => void) | null
let webpackHMR: any let webpackHMR: any
export let router: Router export let router: Router
let CachedComponent: React.ComponentType let CachedComponent: React.ComponentType
let cachedStyleSheets: string[]
let CachedApp: AppComponent, onPerfEntry: (metric: any) => void let CachedApp: AppComponent, onPerfEntry: (metric: any) => void
class Container extends React.Component<{ class Container extends React.Component<{
...@@ -233,7 +241,10 @@ export default async (opts: { webpackHMR?: any } = {}) => { ...@@ -233,7 +241,10 @@ export default async (opts: { webpackHMR?: any } = {}) => {
let initialErr = hydrateErr let initialErr = hydrateErr
try { try {
;({ page: CachedComponent } = await pageLoader.loadPage(page)) ;({
page: CachedComponent,
styleSheets: cachedStyleSheets,
} = await pageLoader.loadPage(page))
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const { isValidElementType } = require('react-is') const { isValidElementType } = require('react-is')
...@@ -291,11 +302,12 @@ export default async (opts: { webpackHMR?: any } = {}) => { ...@@ -291,11 +302,12 @@ export default async (opts: { webpackHMR?: any } = {}) => {
pageLoader, pageLoader,
App: CachedApp, App: CachedApp,
Component: CachedComponent, Component: CachedComponent,
initialStyleSheets: cachedStyleSheets,
wrapApp, wrapApp,
err: initialErr, err: initialErr,
isFallback: Boolean(isFallback), isFallback: Boolean(isFallback),
subscription: ({ Component, props, err }, App) => subscription: ({ Component, styleSheets, props, err }, App) =>
render({ App, Component, props, err }), render({ App, Component, styleSheets, props, err }),
}) })
// call init-client middleware // call init-client middleware
...@@ -314,6 +326,7 @@ export default async (opts: { webpackHMR?: any } = {}) => { ...@@ -314,6 +326,7 @@ export default async (opts: { webpackHMR?: any } = {}) => {
const renderCtx = { const renderCtx = {
App: CachedApp, App: CachedApp,
Component: CachedComponent, Component: CachedComponent,
styleSheets: cachedStyleSheets,
props: hydrateProps, props: hydrateProps,
err: initialErr, err: initialErr,
} }
...@@ -364,6 +377,7 @@ export function renderError(renderErrorProps: RenderErrorProps) { ...@@ -364,6 +377,7 @@ export function renderError(renderErrorProps: RenderErrorProps) {
App: () => null, App: () => null,
props: {}, props: {},
Component: () => null, Component: () => null,
styleSheets: [],
}) })
} }
if (process.env.__NEXT_PLUGINS) { if (process.env.__NEXT_PLUGINS) {
...@@ -383,30 +397,33 @@ export function renderError(renderErrorProps: RenderErrorProps) { ...@@ -383,30 +397,33 @@ export function renderError(renderErrorProps: RenderErrorProps) {
// Make sure we log the error to the console, otherwise users can't track down issues. // Make sure we log the error to the console, otherwise users can't track down issues.
console.error(err) console.error(err)
return pageLoader.loadPage('/_error').then(({ page: ErrorComponent }) => { return pageLoader
// In production we do a normal render with the `ErrorComponent` as component. .loadPage('/_error')
// If we've gotten here upon initial render, we can use the props from the server. .then(({ page: ErrorComponent, styleSheets }) => {
// Otherwise, we need to call `getInitialProps` on `App` before mounting. // In production we do a normal render with the `ErrorComponent` as component.
const AppTree = wrapApp(App) // If we've gotten here upon initial render, we can use the props from the server.
const appCtx = { // Otherwise, we need to call `getInitialProps` on `App` before mounting.
Component: ErrorComponent, const AppTree = wrapApp(App)
AppTree, const appCtx = {
router,
ctx: { err, pathname: page, query, asPath, AppTree },
}
return Promise.resolve(
renderErrorProps.props
? renderErrorProps.props
: loadGetInitialProps(App, appCtx)
).then((initProps) =>
doRender({
...renderErrorProps,
err,
Component: ErrorComponent, Component: ErrorComponent,
props: initProps, AppTree,
}) router,
) ctx: { err, pathname: page, query, asPath, AppTree },
}) }
return Promise.resolve(
renderErrorProps.props
? renderErrorProps.props
: loadGetInitialProps(App, appCtx)
).then((initProps) =>
doRender({
...renderErrorProps,
err,
Component: ErrorComponent,
styleSheets,
props: initProps,
})
)
})
} }
// If hydrate does not exist, eg in preact. // If hydrate does not exist, eg in preact.
...@@ -533,7 +550,13 @@ const wrapApp = (App: AppComponent) => ( ...@@ -533,7 +550,13 @@ const wrapApp = (App: AppComponent) => (
) )
} }
async function doRender({ App, Component, props, err }: RenderRouteInfo) { async function doRender({
App,
Component,
props,
err,
styleSheets,
}: RenderRouteInfo) {
Component = Component || lastAppProps.Component Component = Component || lastAppProps.Component
props = props || lastAppProps.props props = props || lastAppProps.props
...@@ -561,8 +584,99 @@ async function doRender({ App, Component, props, err }: RenderRouteInfo) { ...@@ -561,8 +584,99 @@ async function doRender({ App, Component, props, err }: RenderRouteInfo) {
} }
}) })
// TODO: consider replacing this with real `<style>` tags that have
// plain-text CSS content that's provided by RouteInfo. That'd remove the
// need for the staging `<link>`s and the ability for CSS to be missing at
// this phase, allowing us to remove the error handling flow that reloads the
// page.
function onStart(): Promise<void[]> {
if (
// We can skip this during hydration. Running it wont cause any harm, but
// we may as well save the CPU cycles.
isInitialRender ||
// We use `style-loader` in development, so we don't need to do anything
// unless we're in production:
process.env.NODE_ENV !== 'production'
) {
return Promise.resolve([])
}
let referenceNode: HTMLLinkElement | undefined = ([].slice.call(
document.querySelectorAll('link[data-n-g], link[data-n-p]')
) as HTMLLinkElement[]).pop()
const required: Promise<void>[] = styleSheets.map((href) => {
const [link, promise] = createLink(href, 'stylesheet')
link.setAttribute('data-n-staging', '')
link.setAttribute('media', 'none')
if (referenceNode) {
referenceNode.parentNode!.insertBefore(link, referenceNode.nextSibling)
referenceNode = link
} else {
document.head.appendChild(link)
}
return promise
})
return Promise.all(required).catch(() => {
// This is too late in the rendering lifecycle to use the existing
// `PAGE_LOAD_ERROR` flow (via `handleRouteInfoError`).
// To match that behavior, we request the page to reload with the current
// asPath. This is already set at this phase since we "committed" to the
// render.
// This handles an edge case where a new deployment is rolled during
// client-side transition and the CSS assets are missing.
// This prevents:
// 1. An unstyled page from being rendered (old behavior)
// 2. The `/_error` page being rendered (we want to reload for the new
// deployment)
window.location.href = router.asPath
// Instead of rethrowing the CSS loading error, we give a promise that
// won't resolve. This pauses the rendering process until the page
// reloads. Re-throwing the error could result in a flash of error page.
// throw cssLoadingError
return new Promise(() => {})
})
}
function onAbort() {
document.querySelectorAll('link[data-n-staging]').forEach((el) => {
el.remove()
})
}
renderPromise.catch((abortError) => {
onAbort()
throw abortError
})
function onCommit() {
if (
// We can skip this during hydration. Running it wont cause any harm, but
// we may as well save the CPU cycles.
!isInitialRender &&
// We use `style-loader` in development, so we don't need to do anything
// unless we're in production:
process.env.NODE_ENV === 'production'
) {
// Remove old stylesheets:
document.querySelectorAll('link[data-n-p]').forEach((el) => el.remove())
// Activate new stylesheets:
;[].slice
.call(document.querySelectorAll('link[data-n-staging]'))
.forEach((el: HTMLLinkElement) => {
el.removeAttribute('data-n-staging')
el.removeAttribute('media')
el.setAttribute('data-n-p', '')
})
}
resolvePromise()
}
const elem = ( const elem = (
<Root callback={resolvePromise!}> <Root callback={onCommit}>
<AppContainer> <AppContainer>
<App {...appProps} /> <App {...appProps} />
</AppContainer> </AppContainer>
...@@ -570,6 +684,7 @@ async function doRender({ App, Component, props, err }: RenderRouteInfo) { ...@@ -570,6 +684,7 @@ async function doRender({ App, Component, props, err }: RenderRouteInfo) {
) )
// We catch runtime errors using componentDidCatch which will trigger renderError // We catch runtime errors using componentDidCatch which will trigger renderError
await onStart()
renderReactElement( renderReactElement(
process.env.__NEXT_STRICT_MODE ? ( process.env.__NEXT_STRICT_MODE ? (
<React.StrictMode>{elem}</React.StrictMode> <React.StrictMode>{elem}</React.StrictMode>
......
...@@ -32,6 +32,8 @@ const relPrefetch = ...@@ -32,6 +32,8 @@ const relPrefetch =
// IE 11, Edge 12+, nearly all evergreen // IE 11, Edge 12+, nearly all evergreen
'prefetch' 'prefetch'
const relPreload = hasRel('preload') ? 'preload' : relPrefetch
const hasNoModule = 'noModule' in document.createElement('script') const hasNoModule = 'noModule' in document.createElement('script')
const requestIdleCallback: (fn: () => void) => void = const requestIdleCallback: (fn: () => void) => void =
...@@ -49,30 +51,43 @@ function normalizeRoute(route: string) { ...@@ -49,30 +51,43 @@ function normalizeRoute(route: string) {
return route.replace(/\/$/, '') return route.replace(/\/$/, '')
} }
function appendLink( export function createLink(
href: string, href: string,
rel: string, rel: string,
as?: string, as?: string,
link?: HTMLLinkElement link?: HTMLLinkElement
): Promise<any> { ): [HTMLLinkElement, Promise<any>] {
return new Promise((res, rej) => { link = document.createElement('link')
link = document.createElement('link') return [
link.crossOrigin = process.env.__NEXT_CROSS_ORIGIN! link,
link.href = href new Promise((res, rej) => {
link.rel = rel link!.crossOrigin = process.env.__NEXT_CROSS_ORIGIN!
if (as) link.as = as link!.href = href
link!.rel = rel
link.onload = res if (as) link!.as = as
link.onerror = rej
link!.onload = res
link!.onerror = rej
}),
]
}
document.head.appendChild(link) function appendLink(href: string, rel: string, as?: string): Promise<any> {
}) const [link, res] = createLink(href, rel, as)
document.head.appendChild(link)
return res
} }
export type GoodPageCache = { page: ComponentType; mod: any } export type GoodPageCache = {
page: ComponentType
mod: any
styleSheets: string[]
}
export type PageCacheEntry = { error: any } | GoodPageCache export type PageCacheEntry = { error: any } | GoodPageCache
export default class PageLoader { export default class PageLoader {
private initialPage: string
private initialStyleSheets: string[]
private buildId: string private buildId: string
private assetPrefix: string private assetPrefix: string
private pageCache: Record<string, PageCacheEntry> private pageCache: Record<string, PageCacheEntry>
...@@ -82,7 +97,15 @@ export default class PageLoader { ...@@ -82,7 +97,15 @@ export default class PageLoader {
private promisedSsgManifest?: Promise<ClientSsgManifest> private promisedSsgManifest?: Promise<ClientSsgManifest>
private promisedDevPagesManifest?: Promise<any> private promisedDevPagesManifest?: Promise<any>
constructor(buildId: string, assetPrefix: string, initialPage: string) { constructor(
buildId: string,
assetPrefix: string,
initialPage: string,
initialStyleSheets: string[]
) {
this.initialPage = initialPage
this.initialStyleSheets = initialStyleSheets
this.buildId = buildId this.buildId = buildId
this.assetPrefix = assetPrefix this.assetPrefix = assetPrefix
...@@ -294,13 +317,20 @@ export default class PageLoader { ...@@ -294,13 +317,20 @@ export default class PageLoader {
) { ) {
this.loadScript(d, route) this.loadScript(d, route)
} }
// Prefetch CSS as it'll be needed when the page JavaScript
// evaluates. This will only trigger if explicit prefetching is
// disabled for a <Link>... prefetching in this case is desirable
// because we *know* it's going to be used very soon (page was
// loaded).
if ( if (
d.endsWith('.css') && d.endsWith('.css') &&
!document.querySelector(`link[rel=stylesheet][href^="${d}"]`) !document.querySelector(
`link[rel="${relPreload}"][href^="${d}"]`
)
) { ) {
appendLink(d, 'stylesheet').catch(() => { appendLink(d, relPreload, 'style').catch(() => {
// FIXME: handle failure /* ignore preload error */
// Right now, this is needed to prevent an unhandled rejection.
}) })
} }
}) })
...@@ -334,10 +364,14 @@ export default class PageLoader { ...@@ -334,10 +364,14 @@ export default class PageLoader {
// This method if called by the route code. // This method if called by the route code.
registerPage(route: string, regFn: () => any) { registerPage(route: string, regFn: () => any) {
const register = () => { const register = (styleSheets: string[]) => {
try { try {
const mod = regFn() const mod = regFn()
const pageData = { page: mod.default || mod, mod } const pageData: PageCacheEntry = {
page: mod.default || mod,
mod,
styleSheets,
}
this.pageCache[route] = pageData this.pageCache[route] = pageData
this.pageRegisterEvents.emit(route, pageData) this.pageRegisterEvents.emit(route, pageData)
} catch (error) { } catch (error) {
...@@ -357,7 +391,10 @@ export default class PageLoader { ...@@ -357,7 +391,10 @@ export default class PageLoader {
const check = (status: string) => { const check = (status: string) => {
if (status === 'idle') { if (status === 'idle') {
;(module as any).hot.removeStatusHandler(check) ;(module as any).hot.removeStatusHandler(check)
register() register(
/* css is handled via style-loader in development */
[]
)
} }
} }
;(module as any).hot.status(check) ;(module as any).hot.status(check)
...@@ -365,7 +402,24 @@ export default class PageLoader { ...@@ -365,7 +402,24 @@ export default class PageLoader {
} }
} }
register() const promisedDeps: Promise<string[]> =
// Shared styles will already be on the page:
route === '/_app' ||
// We use `style-loader` in development:
process.env.NODE_ENV !== 'production'
? Promise.resolve([])
: route === this.initialPage
? Promise.resolve(this.initialStyleSheets)
: // Tests that this does not block hydration:
// test/integration/css-fixtures/hydrate-without-deps/
this.getDependencies(route)
promisedDeps.then(
(deps) => register(deps.filter((d) => d.endsWith('.css'))),
(error) => {
this.pageCache[route] = { error }
this.pageRegisterEvents.emit(route, { error })
}
)
} }
/** /**
......
...@@ -159,6 +159,7 @@ export type PrefetchOptions = { ...@@ -159,6 +159,7 @@ export type PrefetchOptions = {
export type PrivateRouteInfo = { export type PrivateRouteInfo = {
Component: ComponentType Component: ComponentType
styleSheets: string[]
__N_SSG?: boolean __N_SSG?: boolean
__N_SSP?: boolean __N_SSP?: boolean
props?: Record<string, any> props?: Record<string, any>
...@@ -257,6 +258,7 @@ export default class Router implements BaseRouter { ...@@ -257,6 +258,7 @@ export default class Router implements BaseRouter {
App, App,
wrapApp, wrapApp,
Component, Component,
initialStyleSheets,
err, err,
subscription, subscription,
isFallback, isFallback,
...@@ -265,6 +267,7 @@ export default class Router implements BaseRouter { ...@@ -265,6 +267,7 @@ export default class Router implements BaseRouter {
initialProps: any initialProps: any
pageLoader: any pageLoader: any
Component: ComponentType Component: ComponentType
initialStyleSheets: string[]
App: AppComponent App: AppComponent
wrapApp: (App: AppComponent) => any wrapApp: (App: AppComponent) => any
err?: Error err?: Error
...@@ -282,6 +285,7 @@ export default class Router implements BaseRouter { ...@@ -282,6 +285,7 @@ export default class Router implements BaseRouter {
if (pathname !== '/_error') { if (pathname !== '/_error') {
this.components[this.route] = { this.components[this.route] = {
Component, Component,
styleSheets: initialStyleSheets,
props: initialProps, props: initialProps,
err, err,
__N_SSG: initialProps && initialProps.__N_SSG, __N_SSG: initialProps && initialProps.__N_SSG,
...@@ -289,7 +293,12 @@ export default class Router implements BaseRouter { ...@@ -289,7 +293,12 @@ export default class Router implements BaseRouter {
} }
} }
this.components['/_app'] = { Component: App as ComponentType } this.components['/_app'] = {
Component: App as ComponentType,
styleSheets: [
/* /_app does not need its stylesheets managed */
],
}
// Backwards compat for Router.router.events // Backwards compat for Router.router.events
// TODO: Should be remove the following major version as it was never documented // TODO: Should be remove the following major version as it was never documented
...@@ -668,8 +677,15 @@ export default class Router implements BaseRouter { ...@@ -668,8 +677,15 @@ export default class Router implements BaseRouter {
} }
try { try {
const { page: Component } = await this.fetchComponent('/_error') const { page: Component, styleSheets } = await this.fetchComponent(
const routeInfo: PrivateRouteInfo = { Component, err, error: err } '/_error'
)
const routeInfo: PrivateRouteInfo = {
Component,
styleSheets,
err,
error: err,
}
try { try {
routeInfo.props = await this.getInitialProps(Component, { routeInfo.props = await this.getInitialProps(Component, {
...@@ -706,6 +722,7 @@ export default class Router implements BaseRouter { ...@@ -706,6 +722,7 @@ export default class Router implements BaseRouter {
? cachedRouteInfo ? cachedRouteInfo
: await this.fetchComponent(route).then((res) => ({ : await this.fetchComponent(route).then((res) => ({
Component: res.page, Component: res.page,
styleSheets: res.styleSheets,
__N_SSG: res.mod.__N_SSG, __N_SSG: res.mod.__N_SSG,
__N_SSP: res.mod.__N_SSP, __N_SSP: res.mod.__N_SSP,
})) }))
......
...@@ -154,9 +154,12 @@ export class Head extends Component< ...@@ -154,9 +154,12 @@ export class Head extends Component<
getCssLinks(files: DocumentFiles): JSX.Element[] | null { getCssLinks(files: DocumentFiles): JSX.Element[] | null {
const { assetPrefix, devOnlyCacheBusterQueryString } = this.context const { assetPrefix, devOnlyCacheBusterQueryString } = this.context
const cssFiles = files.allFiles.filter((f) => f.endsWith('.css')) const cssFiles = files.allFiles.filter((f) => f.endsWith('.css'))
const sharedFiles = new Set(files.sharedFiles)
const cssLinkElements: JSX.Element[] = [] const cssLinkElements: JSX.Element[] = []
cssFiles.forEach((file) => { cssFiles.forEach((file) => {
const isSharedFile = sharedFiles.has(file)
cssLinkElements.push( cssLinkElements.push(
<link <link
key={`${file}-preload`} key={`${file}-preload`}
...@@ -180,6 +183,8 @@ export class Head extends Component< ...@@ -180,6 +183,8 @@ export class Head extends Component<
crossOrigin={ crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
} }
data-n-g={isSharedFile ? '' : undefined}
data-n-p={isSharedFile ? undefined : ''}
/> />
) )
}) })
......
...@@ -94,17 +94,17 @@ describe('Build Output', () => { ...@@ -94,17 +94,17 @@ describe('Build Output', () => {
expect(parseFloat(indexSize) - 265).toBeLessThanOrEqual(0) expect(parseFloat(indexSize) - 265).toBeLessThanOrEqual(0)
expect(indexSize.endsWith('B')).toBe(true) expect(indexSize.endsWith('B')).toBe(true)
// should be no bigger than 60 kb // should be no bigger than 60.1 kb
expect(parseFloat(indexFirstLoad) - 60).toBeLessThanOrEqual(0) expect(parseFloat(indexFirstLoad) - 60.1).toBeLessThanOrEqual(0)
expect(indexFirstLoad.endsWith('kB')).toBe(true) expect(indexFirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(err404Size) - 3.8).toBeLessThanOrEqual(0) expect(parseFloat(err404Size) - 3.8).toBeLessThanOrEqual(0)
expect(err404Size.endsWith('kB')).toBe(true) expect(err404Size.endsWith('kB')).toBe(true)
expect(parseFloat(err404FirstLoad) - 63).toBeLessThanOrEqual(0) expect(parseFloat(err404FirstLoad) - 63.3).toBeLessThanOrEqual(0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll) - 59.6).toBeLessThanOrEqual(0) expect(parseFloat(sharedByAll) - 59.8).toBeLessThanOrEqual(0)
expect(sharedByAll.endsWith('kB')).toBe(true) expect(sharedByAll.endsWith('kB')).toBe(true)
if (_appSize.endsWith('kB')) { if (_appSize.endsWith('kB')) {
...@@ -118,7 +118,7 @@ describe('Build Output', () => { ...@@ -118,7 +118,7 @@ describe('Build Output', () => {
expect(parseFloat(webpackSize) - 752).toBeLessThanOrEqual(0) expect(parseFloat(webpackSize) - 752).toBeLessThanOrEqual(0)
expect(webpackSize.endsWith(' B')).toBe(true) expect(webpackSize.endsWith(' B')).toBe(true)
expect(parseFloat(mainSize) - 6.5).toBeLessThanOrEqual(0) expect(parseFloat(mainSize) - 6.9).toBeLessThanOrEqual(0)
expect(mainSize.endsWith('kB')).toBe(true) expect(mainSize.endsWith('kB')).toBe(true)
expect(parseFloat(frameworkSize) - 41).toBeLessThanOrEqual(0) expect(parseFloat(frameworkSize) - 41).toBeLessThanOrEqual(0)
......
import Link from 'next/link'
import css from './index.module.css'
export default function Home() {
return (
<main>
<Link href="/other">
<a id="link-other">other</a>
</Link>
<br />
<h1 id="black-title" className={css.header}>
Black
</h1>
</main>
)
}
.header {
font-size: 25px;
composes: colorRed from 'common.module.css';
color: #111;
}
import Link from 'next/link'
import css from './other.module.css'
export default function Other() {
return (
<main>
<Link href="/">
<a id="link-index">index page</a>
</Link>
<br />
<h1 id="red-title" className={css.root}>
Red
</h1>
</main>
)
}
.root {
composes: colorRed from './common.module.css';
}
import { useEffect, useState } from 'react'
import css from './index.module.css'
export default function Home() {
const [state, setState] = useState('')
useEffect(() => {
setState('mounted')
}, [])
return (
<main>
<h1 id="black-title" className={css.header}>
Black
</h1>
<p>{state}</p>
</main>
)
}
.header {
font-size: 25px;
composes: colorRed from 'common.module.css';
color: #111;
}
import Link from 'next/link'
import css from './index.module.css'
export default function Home() {
return (
<main>
<Link href="/other">
<a id="link-other">other</a>
</Link>
<br />
<h1 id="black-title" className={css.header}>
Black
</h1>
</main>
)
}
export function getServerSideProps() {
return { props: {} }
}
.header {
font-size: 25px;
composes: colorRed from 'common.module.css';
color: #111;
}
import css from './other.module.css'
export default function Other() {
throw new Error(`oops ${css.root}`)
}
export function getServerSideProps() {
return { props: {} }
}
.root {
composes: colorRed from './common.module.css';
}
import Link from 'next/link'
import css from './index.module.css'
export default function Home() {
return (
<main>
<Link href="/other" prefetch={false}>
<a id="link-other">other</a>
</Link>
<br />
<h1 id="black-title" className={css.header}>
Black
</h1>
</main>
)
}
.header {
font-size: 25px;
composes: colorRed from 'common.module.css';
color: #111;
}
import Link from 'next/link'
import css from './other.module.css'
export default function Other() {
return (
<main>
<Link href="/" prefetch={false}>
<a id="link-index">index page</a>
</Link>
<br />
<h1 id="red-title" className={css.root}>
Red
</h1>
</main>
)
}
.root {
composes: colorRed from './common.module.css';
}
This diff is collapsed.
...@@ -80,7 +80,7 @@ describe('Production response size', () => { ...@@ -80,7 +80,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 276 * 1024 const delta = responseSizesBytes - 277 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
...@@ -100,7 +100,7 @@ describe('Production response size', () => { ...@@ -100,7 +100,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 166 * 1024 const delta = responseSizesBytes - 168 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
......
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