Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

Scripts.tsx

80 lines2.1 KB

1import { Asset } from './Asset'
2import { useRouterState } from './useRouterState'
3import { useRouter } from './useRouter'
4import type { RouterManagedTag } from '@tanstack/router-core'
5​
6/**
7 * Render body script tags collected from route matches and SSR manifests.
8 * Should be placed near the end of the document body.
9 */
10export const Scripts = () => {
11 const router = useRouter()
12 const nonce = router.options.ssr?.nonce
13 const assetScripts = useRouterState({
14 select: (state) => {
15 const assetScripts: Array<RouterManagedTag> = []
16 const manifest = router.ssr?.manifest
17​
18 if (!manifest) {
19 return []
20 }
21​
22 state.matches
23 .map((match) => router.looseRoutesById[match.routeId]!)
24 .forEach((route) =>
25 manifest.routes[route.id]?.assets
26 ?.filter((d) => d.tag === 'script')
27 .forEach((asset) => {
28 assetScripts.push({
29 tag: 'script',
30 attrs: { ...asset.attrs, nonce },
31 children: asset.children,
32 } as any)
33 }),
34 )
35​
36 return assetScripts
37 },
38 structuralSharing: true as any,
39 })
40​
41 const { scripts } = useRouterState({
42 select: (state) => ({
43 scripts: (
44 state.matches
45 .map((match) => match.scripts!)
46 .flat(1)
47 .filter(Boolean) as Array<RouterManagedTag>
48 ).map(({ children, ...script }) => ({
49 tag: 'script',
50 attrs: {
51 ...script,
52 suppressHydrationWarning: true,
53 nonce,
54 },
55 children,
56 })),
57 }),
58 structuralSharing: true as any,
59 })
60​
61 let serverBufferedScript: RouterManagedTag | undefined = undefined
62​
63 if (router.serverSsr) {
64 serverBufferedScript = router.serverSsr.takeBufferedScripts()
65 }
66​
67 const allScripts = [...scripts, ...assetScripts] as Array<RouterManagedTag>
68​
69 if (serverBufferedScript) {
70 allScripts.unshift(serverBufferedScript)
71 }
72​
73 return (
74 <>
75 {allScripts.map((asset, i) => (
76 <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
77 ))}
78 </>
79 )