TanStack Start 中文文档
服务器与执行

环境函数(Environment Functions)

什么是环境函数?

环境函数(Environment Functions)是用来根据运行时环境——代码运行在客户端还是服务端——定义和控制函数执行的工具函数。这些工具能确保环境专属的逻辑被安全、有意识地执行,防止运行时错误,并提高全栈或同构应用的可维护性。

Start 提供三个核心环境函数:

  • createIsomorphicFn:组合一个能适配客户端和服务端两种环境的函数。
  • createServerOnlyFn:创建一个只能在服务器上运行的函数。
  • createClientOnlyFn:创建一个只能在客户端上运行的函数。

同构函数

createIsomorphicFn() 定义在客户端或服务端调用时行为不同的函数。这在跨环境安全地共享逻辑、同时把环境专属的行为委托给合适的 handler 时非常有用。

完整实现

import { createIsomorphicFn } from '@tanstack/react-start'

const getEnv = createIsomorphicFn()
  .server(() => 'server')
  .client(() => 'client')

const env = getEnv()
// ℹ️ On the **server**, it returns `'server'`.
// ℹ️ On the **client**, it returns `'client'`.

部分实现(仅服务端)

下面是一个只有服务端实现的 createIsomorphicFn() 示例:

import { createIsomorphicFn } from '@tanstack/react-start'

const serverImplementationOnly = createIsomorphicFn().server(() => 'server')

const server = serverImplementationOnly()
// ℹ️ On the **server**, it returns `'server'`.
// ℹ️ On the **client**, it is no-op (returns `undefined`)

部分实现(仅客户端)

下面是一个只有客户端实现的 createIsomorphicFn() 示例:

import { createIsomorphicFn } from '@tanstack/react-start'

const clientImplementationOnly = createIsomorphicFn().client(() => 'client')

const client = clientImplementationOnly()
// ℹ️ On the **server**, it is no-op (returns `undefined`)
// ℹ️ On the **client**, it returns `'client'`.

无实现

下面是一个没有任何环境专属实现的 createIsomorphicFn() 示例:

import { createIsomorphicFn } from '@tanstack/react-start'

const noImplementation = createIsomorphicFn()

const noop = noImplementation()
// ℹ️ On both **client** and **server**, it is no-op (returns `undefined`)

什么是 no-op?

no-op("no operation" 的缩写)指的是执行时什么都不做的函数——它只是返回 undefined,不做任何操作。

// basic no-op implementation
function noop() {}

env 函数

createServerOnlyFncreateClientOnlyFn 这两个辅助函数强制执行严格的环境限定。它们确保返回的函数只能在正确的运行时上下文中调用。如果误用,它们会抛出带有描述信息的运行时错误,防止意外执行逻辑。

createServerOnlyFn

import { createServerOnlyFn } from '@tanstack/react-start'

const foo = createServerOnlyFn(() => 'bar')

foo() // ✅ On server: returns "bar"
// ❌ On client: throws "createServerOnlyFn() functions can only be called on the server!"

createClientOnlyFn

import { createClientOnlyFn } from '@tanstack/react-start'

const foo = createClientOnlyFn(() => 'bar')

foo() // ✅ On client: returns "bar"
// ❌ On server: throws "createClientOnlyFn() functions can only be called on the client!"

注意

这些函数适用于 API 访问、文件系统读取、使用浏览器 API,以及其他在目标环境之外调用会无效或不安全的操作。

Tree Shaking

环境函数会根据每个打包产物对应的环境进行 tree-shaking。

使用 createIsomorphicFn() 创建的函数会被 tree-shake。.client() 内的所有代码都不会包含在服务端打包产物中,反之亦然。

在服务端,用 createClientOnlyFn() 创建的函数会被替换成一个在服务端抛 Error 的函数。createServerOnlyFn 函数在客户端的情况与之相反。

On this page