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

Scripts.tsx

53 lines1.7 KB

1import * as Solid from 'solid-js'
2import { _getAssetMatches, replaceEqualDeep } from '@tanstack/router-core'
3import { isServer } from '@tanstack/router-core/isServer'
4import { Asset } from './Asset'
5import { useRouter } from './useRouter'
6import type { RouterManagedTag } from '@tanstack/router-core'
7​
8export const Scripts = () => {
9 const router = useRouter()
10 const nonce = router.options.ssr?.nonce
11​
12 const scripts = Solid.createMemo(
13 (previous: Array<RouterManagedTag> | undefined) => {
14 const matches = _getAssetMatches(router.stores.matches.get())
15 const next: Array<RouterManagedTag> = []
16 const assets: Array<RouterManagedTag> = []
17 const manifest = router.ssr?.manifest
18 for (const match of matches) {
19 for (const script of match.scripts ?? []) {
20 if (!script) {
21 continue
22 }
23 const { children, ...attrs } = script
24 next.push({
25 tag: 'script',
26 attrs: { ...attrs, nonce },
27 children: children as string | undefined,
28 })
29 }
30 for (const asset of manifest?.routes[match.routeId]?.scripts ?? []) {
31 assets.push({
32 tag: 'script',
33 attrs: { ...asset.attrs, nonce },
34 children: asset.children,
35 })
36 }
37 }
38 next.push(...assets)
39 return previous ? replaceEqualDeep(previous, next) : next
40 },
41 )
42 const serverBufferedScript =
43 (isServer ?? router.isServer) && router.serverSsr
44 ? router.serverSsr.takeBufferedScripts()
45 : undefined
46​
47 return (
48 <>
49 {serverBufferedScript && <Asset {...serverBufferedScript} />}
50 <Solid.For each={scripts()}>{(asset) => <Asset {...asset} />}</Solid.For>
51 </>
52 )