Unverified Commit 8aebac17 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Development: Don't import app-router / hot-reloader through next/link in application code (#83656)

## What?

Removes imports from the app-ssr layer that cause transitive
dependencies to be included during compilation in development.

For the trace that I received from an application there was quite a bit
of overhead for them because of this issue.

Trace:

![CleanShot 2025-09-10 at
21.32.27@2x.png](https://app.graphite.dev/user-attachments/assets/8a7e5323-ed3c-4aec-8723-7fbbae89a99d.png)
parent a64c5915
...@@ -18,7 +18,6 @@ import { ...@@ -18,7 +18,6 @@ import {
type LinkInstance, type LinkInstance,
} from '../components/links' } from '../components/links'
import { isLocalURL } from '../../shared/lib/router/utils/is-local-url' import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import { dispatchNavigateAction } from '../components/app-router-instance'
import { import {
FetchStrategy, FetchStrategy,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
...@@ -221,6 +220,7 @@ function linkClicked( ...@@ -221,6 +220,7 @@ function linkClicked(
scroll?: boolean, scroll?: boolean,
onNavigate?: OnNavigateEventHandler onNavigate?: OnNavigateEventHandler
): void { ): void {
if (typeof window !== 'undefined') {
if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) { if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
// ignore click for browser’s default behavior // ignore click for browser’s default behavior
return return
...@@ -254,6 +254,9 @@ function linkClicked( ...@@ -254,6 +254,9 @@ function linkClicked(
} }
} }
const { dispatchNavigateAction } =
require('../components/app-router-instance') as typeof import('../components/app-router-instance')
React.startTransition(() => { React.startTransition(() => {
dispatchNavigateAction( dispatchNavigateAction(
as || href, as || href,
...@@ -262,6 +265,7 @@ function linkClicked( ...@@ -262,6 +265,7 @@ function linkClicked(
linkInstanceRef.current linkInstanceRef.current
) )
}) })
}
} }
function formatStringOrUrl(urlObjOrString: UrlObject | string): string { function formatStringOrUrl(urlObjOrString: UrlObject | string): string {
......
...@@ -21,7 +21,7 @@ import { ...@@ -21,7 +21,7 @@ import {
} from './segment-cache' } from './segment-cache'
import { dispatchAppRouterAction } from './use-action-queue' import { dispatchAppRouterAction } from './use-action-queue'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { createPrefetchURL, isExternalURL } from './app-router' import { createPrefetchURL, isExternalURL } from './app-router-utils'
import { prefetchReducer } from './router-reducer/reducers/prefetch-reducer' import { prefetchReducer } from './router-reducer/reducers/prefetch-reducer'
import type { import type {
AppRouterInstance, AppRouterInstance,
......
import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path'
export function isExternalURL(url: URL) {
return url.origin !== window.location.origin
}
/**
* Given a link href, constructs the URL that should be prefetched. Returns null
* in cases where prefetching should be disabled, like external URLs, or
* during development.
* @param href The href passed to <Link>, router.prefetch(), or similar
* @returns A URL object to prefetch, or null if prefetching should be disabled
*/
export function createPrefetchURL(href: string): URL | null {
// Don't prefetch for bots as they don't navigate.
if (isBot(window.navigator.userAgent)) {
return null
}
let url: URL
try {
url = new URL(addBasePath(href), window.location.href)
} catch (_) {
// TODO: Does this need to throw or can we just console.error instead? Does
// anyone rely on this throwing? (Seems unlikely.)
throw new Error(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
}
// Don't prefetch during development (improves compilation performance)
if (process.env.NODE_ENV === 'development') {
return null
}
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return null
}
return url
}
'use client'
import React, { import React, {
useEffect, useEffect,
useMemo, useMemo,
...@@ -25,8 +23,6 @@ import { ...@@ -25,8 +23,6 @@ import {
PathParamsContext, PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { dispatchAppRouterAction, useActionQueue } from './use-action-queue' import { dispatchAppRouterAction, useActionQueue } from './use-action-queue'
import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary' import { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache' import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
...@@ -53,47 +49,6 @@ const globalMutable: { ...@@ -53,47 +49,6 @@ const globalMutable: {
pendingMpaPath?: string pendingMpaPath?: string
} = {} } = {}
export function isExternalURL(url: URL) {
return url.origin !== window.location.origin
}
/**
* Given a link href, constructs the URL that should be prefetched. Returns null
* in cases where prefetching should be disabled, like external URLs, or
* during development.
* @param href The href passed to <Link>, router.prefetch(), or similar
* @returns A URL object to prefetch, or null if prefetching should be disabled
*/
export function createPrefetchURL(href: string): URL | null {
// Don't prefetch for bots as they don't navigate.
if (isBot(window.navigator.userAgent)) {
return null
}
let url: URL
try {
url = new URL(addBasePath(href), window.location.href)
} catch (_) {
// TODO: Does this need to throw or can we just console.error instead? Does
// anyone rely on this throwing? (Seems unlikely.)
throw new Error(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
}
// Don't prefetch during development (improves compilation performance)
if (process.env.NODE_ENV === 'development') {
return null
}
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return null
}
return url
}
function HistoryUpdater({ function HistoryUpdater({
appRouterState, appRouterState,
}: { }: {
......
import type { FlightRouterState } from '../../shared/lib/app-router-types' import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime' import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { getCurrentAppRouterState } from './app-router-instance'
import { createPrefetchURL } from './app-router'
import { import {
FetchStrategy, FetchStrategy,
isPrefetchTaskDirty, isPrefetchTaskDirty,
...@@ -122,6 +120,10 @@ function observeVisibility(element: Element, instance: PrefetchableInstance) { ...@@ -122,6 +120,10 @@ function observeVisibility(element: Element, instance: PrefetchableInstance) {
} }
function coercePrefetchableUrl(href: string): URL | null { function coercePrefetchableUrl(href: string): URL | null {
if (typeof window !== 'undefined') {
const { createPrefetchURL } =
require('./app-router-utils') as typeof import('./app-router-utils')
try { try {
return createPrefetchURL(href) return createPrefetchURL(href)
} catch { } catch {
...@@ -137,6 +139,9 @@ function coercePrefetchableUrl(href: string): URL | null { ...@@ -137,6 +139,9 @@ function coercePrefetchableUrl(href: string): URL | null {
) )
return null return null
} }
} else {
return null
}
} }
export function mountLinkInstance( export function mountLinkInstance(
...@@ -274,6 +279,8 @@ function rescheduleLinkPrefetch( ...@@ -274,6 +279,8 @@ function rescheduleLinkPrefetch(
instance: PrefetchableInstance, instance: PrefetchableInstance,
priority: PrefetchPriority.Default | PrefetchPriority.Intent priority: PrefetchPriority.Default | PrefetchPriority.Intent
) { ) {
// Ensures that app-router-instance is not compiled in the server bundle
if (typeof window !== 'undefined') {
const existingPrefetchTask = instance.prefetchTask const existingPrefetchTask = instance.prefetchTask
if (!instance.isVisible) { if (!instance.isVisible) {
...@@ -296,6 +303,9 @@ function rescheduleLinkPrefetch( ...@@ -296,6 +303,9 @@ function rescheduleLinkPrefetch(
return return
} }
const { getCurrentAppRouterState } =
require('./app-router-instance') as typeof import('./app-router-instance')
const appRouterState = getCurrentAppRouterState() const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) { if (appRouterState !== null) {
const treeAtTimeOfPrefetch = appRouterState.tree const treeAtTimeOfPrefetch = appRouterState.tree
...@@ -321,6 +331,7 @@ function rescheduleLinkPrefetch( ...@@ -321,6 +331,7 @@ function rescheduleLinkPrefetch(
) )
} }
} }
}
} }
export function pingVisibleLinks( export function pingVisibleLinks(
......
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { createPrefetchURL } from '../app-router' import { createPrefetchURL } from '../app-router-utils'
import { createCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
import { schedulePrefetchTask } from './scheduler' import { schedulePrefetchTask } from './scheduler'
import { import {
......
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