|
| 1 | +# Example of a monorepo with router and feature libraries, using lazy loading |
| 2 | + |
| 3 | +To run this example: |
| 4 | + |
| 5 | +- `npm install` or `yarn` |
| 6 | +- `npm dev` or `yarn dev` |
| 7 | + |
| 8 | +A challenge with TanStack Router in a monorepo setup is that it requires TypeScript type augmentations. However, if you set this up directly in the final app, the links inside the libraries won’t be type-safe. To solve this in a monorepo, you need a separate library just for the router, without any components, and then integrate it with the app. |
| 9 | + |
| 10 | +This example showcases this approach using the following packages: |
| 11 | + |
| 12 | +- `packages/router` is the router library |
| 13 | +- `packages/post-feature` is the posts UI library |
| 14 | +- `packages/app` is the app |
| 15 | + |
| 16 | +With this approach, we can use loaders in the router and the feature library without creating circular dependencies. |
| 17 | + |
| 18 | +Since the router library re-exports the router components, importing them in the feature library ensures they remain type-safe, as they’re linked to the TypeScript augmentations. |
| 19 | + |
| 20 | +Finally, in the app, we can create a map of routes to components ([`packages/app/src/main.tsx`](./packages/app/src/main.tsx)), which ties the router to the components. |
| 21 | + |
| 22 | +## How lazy loading works |
| 23 | + |
| 24 | +Eath feature exports a `createLazyRoute` function that returns a lazy route. This lazy route is then used in the router map to bind the lazy route to the actual route. This allows library to define their component, pending, error and nod found components directly. |
| 25 | + |
| 26 | +The types on the ([`packages/app/src/main.tsx`](./packages/app/src/main.tsx)) are used to map the route to the lazy route, and enforce they match the route path. |
| 27 | + |
| 28 | +**Note: if you match a lazy route with a different id of the route, you will get a runtime error, hence the mapped types to ensure we are also warned by typescript.** |
| 29 | + |
| 30 | +Here is what it looks like in the monorepo: |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +## Stackblitz limitation |
| 35 | + |
| 36 | +### Typescript IDE feedback |
| 37 | + |
| 38 | +Due to a limitation on Stackblitz, the example's types are not properly inferred in the IDE, however as soon as you click on fork in the bottom right corner, the types should be correctly inferred. |
0 commit comments