Skip to content

Commit

Permalink
fix: prefer granular routeConfigs, support type-safe library exports
Browse files Browse the repository at this point in the history
  • Loading branch information
tannerlinsley committed Nov 18, 2022
1 parent 0bacb29 commit 5ee825f
Show file tree
Hide file tree
Showing 55 changed files with 990 additions and 700 deletions.
4 changes: 2 additions & 2 deletions docs/devtools.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function App() {
return (
<>
<Router router={router} />
<TanStackRouterDevtools router={router} />
<TanStackRouterDevtools />
</>
)
}
Expand All @@ -72,7 +72,7 @@ function App() {
return (
<>
<Router />
<TanStackRouterDevtools router={router} initialIsOpen={false} />
<TanStackRouterDevtools initialIsOpen={false} />
</>
)
}
Expand Down
3 changes: 1 addition & 2 deletions docs/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ function App() {
<>
<RouterProvider router={router}>
<div>
<router.Link to="/">Home</router.Link>{' '}
<router.Link to="/about">About</router.Link>
<Link to="/">Home</Link> <Link to="/about">About</Link>
</div>
<hr />
<Outlet />
Expand Down
3 changes: 2 additions & 1 deletion examples/react/basic-ssr-lite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"dev": "node server",
"build": "npm run build:client && npm run build:server",
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --ssr src/entry-server.jsx --outDir dist/server",
"build:server": "vite build --ssr src/entry-server.tsx --outDir dist/server",
"serve": "NODE_ENV=production node server",
"debug": "node --inspect-brk server"
},
Expand All @@ -20,6 +20,7 @@
},
"devDependencies": {
"@babel/core": "^7.20.2",
"@babel/generator": "^7.20.4",
"@rollup/plugin-babel": "^6.0.2",
"@types/jsesc": "^3.0.1",
"@vitejs/plugin-react": "^2.2.0",
Expand Down
30 changes: 21 additions & 9 deletions examples/react/basic-ssr-lite/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,28 @@ export async function createServer(
return res.status(404)
}

let template, render
const { template, render, load } = await (async () => {
if (!isProd) {
// always read fresh template in dev
let template = fs.readFileSync(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
return {
template,
...(await vite.ssrLoadModule('/src/entry-server.tsx')),
}
} else {
return {
template: indexProd,
...(await import('./dist/server/entry-server.tsx')),
}
}
})()

if (!isProd) {
// always read fresh template in dev
template = fs.readFileSync(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
render = (await vite.ssrLoadModule('/src/entry-server.tsx')).render
} else {
template = indexProd
render = (await import('./dist/server/entry-server.tsx')).render
if (url.includes('__data=')) {
const data = await load({
url,
})
return res.json(data)
}

render({ template, url, res })
Expand Down
15 changes: 6 additions & 9 deletions examples/react/basic-ssr-lite/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,32 @@
import * as React from 'react'
import { Outlet } from '@tanstack/react-router'
import { Link, Outlet } from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'

import { router } from './router'

export function App() {
return (
// Build our routes and render our router
<>
<div>
<router.Link
<Link
to="/"
activeProps={{
className: 'font-bold',
}}
activeOptions={{ exact: true }}
>
Home
</router.Link>{' '}
<router.Link
</Link>{' '}
<Link
to="/posts"
activeProps={{
className: 'font-bold',
}}
>
Posts
</router.Link>
</Link>
</div>
<hr />
<Outlet />
<TanStackRouterDevtools router={router} />
<TanStackRouterDevtools />
</>
)
}
10 changes: 3 additions & 7 deletions examples/react/basic-ssr-lite/src/entry-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import * as React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from '@tanstack/react-router'

import { router } from './router'
import { createRouter } from './router'
import { App } from './App'

const router = createRouter()

const state = (window as any).__TANSTACK_ROUTER_STATE__

router.hydrateState(state)
Expand All @@ -15,9 +17,3 @@ ReactDOM.hydrateRoot(
<App />
</RouterProvider>,
)

// ReactDOM.createRoot(document.getElementById('root')!).render(
// <RouterProvider router={router}>
// <App />
// </RouterProvider>,
// )
33 changes: 27 additions & 6 deletions examples/react/basic-ssr-lite/src/entry-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ import ReactDOMServer from 'react-dom/server'
import { createMemoryHistory, RouterProvider } from '@tanstack/react-router'
import jsesc from 'jsesc'
import { App } from './App'
import { router } from './router'
import { ServerResponse } from 'http'
import { createRouter } from './router'

async function getRouter(opts: { url: string }) {
const router = createRouter()

export async function render(opts: {
url: string
template: string
res: ServerResponse
}) {
router.reset()

const memoryHistory = createMemoryHistory({
Expand All @@ -23,6 +21,27 @@ export async function render(opts: {

router.mount()() // and unsubscribe immediately

return router
}

export async function load(opts: { url: string }) {
const router = await getRouter(opts)

await router.load()

const search = router.state.location.search as { __data: { matchId: string } }

return router.state.matches.find((d) => d.matchId === search.__data.matchId)
?.routeLoaderData
}

export async function render(opts: {
url: string
template: string
res: ServerResponse
}) {
const router = await getRouter(opts)

router.load().then(() => {
const routerState = router.dehydrateState()
const routerScript = `<script>window.__TANSTACK_ROUTER_STATE__ = JSON.parse(${jsesc(
Expand All @@ -35,6 +54,8 @@ export async function render(opts: {
)})</script>`

opts.res.write(routerScript)

return router
})

const leadingHtml = opts.template.substring(
Expand Down
71 changes: 39 additions & 32 deletions examples/react/basic-ssr-lite/src/routeConfig.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,49 @@
import * as React from 'react'
import { createRouteConfig, Outlet } from '@tanstack/react-router'
import { createRouteConfig, Outlet, useMatch } from '@tanstack/react-router'
import axios from 'axios'
import { router } from './router'

type PostType = {
id: string
title: string
body: string
}

export const routeConfig = createRouteConfig().createChildren((createRoute) => [
createRoute({
path: '/',
component: Index,
}),
createRoute({
path: 'posts',
component: Posts,
errorComponent: () => 'Oh crap!',
loader: async () => {
return {
posts: await fetchPosts(),
}
},
// loader: {...}
}).createChildren((createRoute) => [
createRoute({ path: '/', component: PostsIndex }),
createRoute({
path: ':postId',
component: Post,
loader: async ({ params: { postId } }) => {
return {
post: await fetchPostById(postId),
}
},
// loader: {...}
}),
]),
const rootRoute = createRouteConfig()

const indexRoute = rootRoute.createRoute({
path: '/',
component: Index,
})

const postsRoute = rootRoute.createRoute({
path: 'posts',
component: Posts,
errorComponent: () => 'Oh crap',
loader: async () => {
return {
posts: await fetchPosts(),
}
},
})

const PostsIndexRoute = postsRoute.createRoute({
path: '/',
component: PostsIndex,
})

const postRoute = postsRoute.createRoute({
path: ':postId',
component: Post,
loader: async ({ params: { postId } }) => {
return {
post: await fetchPostById(postId),
}
},
})

export const routeConfig = createRouteConfig().addChildren([
indexRoute,
postsRoute.addChildren([PostsIndexRoute, postRoute]),
])

async function fetchPosts() {
Expand Down Expand Up @@ -68,7 +75,7 @@ function Posts() {
const {
loaderData: { posts },
Link,
} = router.useMatch('/posts')
} = useMatch(postsRoute.id)

return (
<div>
Expand Down Expand Up @@ -110,7 +117,7 @@ function PostsIndex() {
function Post() {
const {
loaderData: { post },
} = router.useMatch('/posts/:postId')
} = useMatch(postRoute.id)

return (
<div>
Expand Down
15 changes: 10 additions & 5 deletions examples/react/basic-ssr-lite/src/router.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { createReactRouter } from '@tanstack/react-router'
import { routeConfig } from './routeConfig'

// Set up a ReactRouter instance
export const createRouter = () =>
createReactRouter({
routeConfig,
// defaultPreload: 'intent',
})

export const router = createReactRouter({
routeConfig,
// defaultPreload: 'intent',
})
declare module '@tanstack/react-router' {
interface ResolveRouter {
router: ReturnType<typeof createRouter>
}
}
Loading

0 comments on commit 5ee825f

Please sign in to comment.