Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: added section how to survive require cache purge in dev #8437

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@
- goncy
- gonzoscript
- graham42
- gramotei
- GregBrimble
- GSt4r
- guatedude2
Expand Down
31 changes: 31 additions & 0 deletions docs/discussion/hot-module-replacement.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,34 @@ In some cases, React cannot distinguish between existing components being change
[meta]: ../route/meta
[use-loader-data]: ../hooks/use-loader-data
[react-keys]: https://react.dev/learn/rendering-lists#why-does-react-need-keys

## Survive 'require' Cache Purge

Remix purges the require cache on every request in development to support `<LiveReload/>`. To make sure your cache survives these purges, you need to assign it to the global object.

```ts
// utils/singleton.server.ts

// since the dev server re-requires the bundle, do some shenanigans to make
// certain things persist across that 😆
// Borrowed/modified from https://github.com/jenseng/abuse-the-platform/blob/2993a7e846c95ace693ce61626fa072174c8d9c7/app/utils/singleton.ts

export function singleton<Value>(name: string, value: () => Value): Value {
const yolo = global as any
yolo.__singletons ??= {}
yolo.__singletons[name] ??= value()
return yolo.__singletons[name]
}
```

```ts
// utils/prisma.server.ts

import { PrismaClient } from '@prisma/client'
import { singleton } from './singleton.server.ts'

const prisma = singleton('prisma', () => new PrismaClient())
prisma.$connect()

export { prisma }
```