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

dead-code-preserve.tsx

61 lines1.9 KB

1import { createFileRoute } from '@tanstack/solid-router'
2import * as fs from 'node:fs'
3import { createServerFn } from '@tanstack/solid-start'
4import { getRequestHeader } from '@tanstack/solid-start/server'
5import { createSignal } from 'solid-js'
6import {} from '@tanstack/solid-router'
7​
8export const Route = createFileRoute('/dead-code-preserve')({
9 component: RouteComponent,
10})
11​
12// by using this we make sure DCE still works - this errors when imported on the client
13​
14const filePath = 'count-effect.txt'
15​
16async function readCount() {
17 return parseInt(
18 await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
19 )
21​
22async function updateCount() {
23 const count = await readCount()
24 await fs.promises.writeFile(filePath, `${count + 1}`)
25 return true
27​
28const writeFileServerFn = createServerFn().handler(async () => {
29 // eslint-disable-next-line unused-imports/no-unused-vars
30 const test = await updateCount()
31 return getRequestHeader('X-Test')
32})
33​
34const readFileServerFn = createServerFn().handler(async () => {
35 const data = await readCount()
36 return data
37})
38​
39function RouteComponent() {
40 const [serverFnOutput, setServerFnOutput] = createSignal<number>()
41 return (
42 <div class="p-2 m-2 grid gap-2">
43 <h3>Dead code test</h3>
44 <p>
45 This server function writes to a file as a side effect, then reads it.
46 </p>
47 <button
48 class="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-xs ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
49 data-testid="test-dead-code-fn-call-btn"
50 onClick={async () => {
51 await writeFileServerFn({ headers: { 'X-Test': 'test' } })
52 setServerFnOutput(await readFileServerFn())
53 }}
54 >
55 Call Dead Code Fn
56 </button>
57 <h4>Server output</h4>
58 <pre data-testid="dead-code-fn-call-response">{serverFnOutput()}</pre>
59 </div>
60 )