Skip to content

Commit 8118f6f

Browse files
authored
Merge pull request #913 from vitejs/feature/translate-api-vite-runtime
docs(cn): translate api-vite-runtime.md
2 parents 4c6eeb2 + 7fd93de commit 8118f6f

File tree

2 files changed

+53
-53
lines changed

2 files changed

+53
-53
lines changed

guide/api-javascript.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# JavaScript API {#javascript-api}
22

3-
Vite 的 JavaScript API 是完全类型化的,我们推荐使用 TypeScript 或者在 VS Code 中启用 JS 类型检查来利用智能提示和类型校验
3+
Vite 的 JavaScript API 是完全类型化的,我们推荐使用 TypeScript 或者在 VS Code 中启用 JS 类型检查来利用智能提示和类型签名
44

55
## `createServer` {#createserver}
66

@@ -186,7 +186,7 @@ interface ViteDevServer {
186186

187187
## `build` {#build}
188188

189-
**类型校验**
189+
**类型签名**
190190

191191
```ts
192192
async function build(
@@ -281,7 +281,7 @@ interface PreviewServer {
281281

282282
## `resolveConfig` {#resolveconfig}
283283

284-
**类型校验**
284+
**类型签名**
285285

286286
```ts
287287
async function resolveConfig(

guide/api-vite-runtime.md

+50-50
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1-
# Vite Runtime API
1+
# Vite 运行时 API {#vite-runtime-api}
22

3-
:::warning Low-level API
4-
This API was introduced in Vite 5.1 as an experimental feature. It was added to [gather feedback](https://github.com/vitejs/vite/discussions/15774). There will probably be breaking changes to it in Vite 5.2, so make sure to pin the Vite version to `~5.1.0` when using it. This is a low-level API meant for library and framework authors. If your goal is to create an application, make sure to check out the higher-level SSR plugins and tools at [Awesome Vite SSR section](https://github.com/vitejs/awesome-vite#ssr) first.
3+
:::warning 低级别 API
4+
这个 API Vite 5.1 中作为一个实验性特性引入。它被添加以 [收集反馈](https://github.com/vitejs/vite/discussions/15774)。在Vite 5.2 中,它可能会有破坏性的变化,所以在使用它时,请确保将 Vite 版本固定在 `~5.1.0`。这是一个面向库和框架作者的低级别 API。如果你的目标是开发应用,请确保首先查看 [Vite SSR 精选板块](https://github.com/vitejs/awesome-vite#ssr) 的高级 SSR 插件和工具。
55
:::
66

7-
The "Vite Runtime" is a tool that allows running any code by processing it with Vite plugins first. It is different from `server.ssrLoadModule` because the runtime implementation is decoupled from the server. This allows library and framework authors to implement their own layer of communication between the server and the runtime.
7+
"Vite 运行时" 是一个工具,它允许首先用 Vite 插件处理任何代码后运行。它与 `server.ssrLoadModule` 不同,因为运行时实现是从服务器解耦的。这允许库和框架作者实现他们自己的服务器和运行时之间的通信层。
88

9-
One of the goals of this feature is to provide a customizable API to process and run the code. Vite provides enough tools to use Vite Runtime out of the box, but users can build upon it if their needs do not align with Vite's built-in implementation.
9+
这个特性的一个目标是提供一个可定制的API来处理和运行代码。Vite 提供了足够的工具来开箱即用 Vite 运行时,但如果用户的需求与 Vite 的内置实现不一致,他们可以在其基础上进行构建。
1010

11-
All APIs can be imported from `vite/runtime` unless stated otherwise.
11+
除非另有说明,所有API都可以从 `vite/runtime` 导入。
1212

1313
## `ViteRuntime`
1414

15-
**Type Signature:**
15+
**类型签名:**
1616

1717
```ts
1818
export class ViteRuntime {
@@ -22,42 +22,42 @@ export class ViteRuntime {
2222
private debug?: ViteRuntimeDebugger,
2323
) {}
2424
/**
25-
* URL to execute. Accepts file path, server path, or id relative to the root.
25+
* 要执行的 URL。可以是文件路径、服务器路径,或者是相对于根目录的 id。
2626
*/
2727
public async executeUrl<T = any>(url: string): Promise<T>
2828
/**
29-
* Entry point URL to execute. Accepts file path, server path or id relative to the root.
30-
* In the case of a full reload triggered by HMR, this is the module that will be reloaded.
31-
* If this method is called multiple times, all entry points will be reloaded one at a time.
29+
* 执行的入口文件 URL。可以是文件路径、服务器路径,或者是相对于根目录的 id。
30+
* 如果是由 HMR 触发的全面重载,那么这就是将要被重载的模块。
31+
* 如果这个方法被多次调用,所有的入口文件都将逐一被重新加载。
3232
*/
3333
public async executeEntrypoint<T = any>(url: string): Promise<T>
3434
/**
35-
* Clear all caches including HMR listeners.
35+
* 清除所有缓存,包括 HMR 监听器。
3636
*/
3737
public clearCache(): void
3838
/**
39-
* Clears all caches, removes all HMR listeners, and resets source map support.
40-
* This method doesn't stop the HMR connection.
39+
* 清除所有缓存,移除所有 HMR 监听器,并重置 sourcemap 支持。
40+
* 此方法不会停止 HMR 连接。
4141
*/
4242
public async destroy(): Promise<void>
4343
/**
44-
* Returns `true` if the runtime has been destroyed by calling `destroy()` method.
44+
* 如果通过调用 `destroy()` 方法销毁了运行时,则返回 `true`。
4545
*/
4646
public isDestroyed(): boolean
4747
}
4848
```
4949

50-
::: tip Advanced Usage
51-
If you are just migrating from `server.ssrLoadModule` and want to support HMR, consider using [`createViteRuntime`](#createviteruntime) instead.
50+
::: tip 进阶用法
51+
如果你是从 `server.ssrLoadModule` 迁移过来,并且想要支持热模块替换(HMR),你可以考虑用 [`createViteRuntime`](#createviteruntime) 替代。
5252
:::
5353

54-
The `ViteRuntime` class requires `root` and `fetchModule` options when initiated. Vite exposes `ssrFetchModule` on the [`server`](/guide/api-javascript) instance for easier integration with Vite SSR. Vite also exports `fetchModule` from its main entry point - it doesn't make any assumptions about how the code is running unlike `ssrFetchModule` that expects the code to run using `new Function`. This can be seen in source maps that these functions return.
54+
当你初始化 `ViteRuntime` 类时,需要 `root` `fetchModule` 这两个选项。Vite [`server`](/guide/api-javascript) 实例中公开了 `ssrFetchModule`,以便更方便地与 Vite SSR 集成。Vite 主入口也导出了 `fetchModule` - 它不会假设代码的运行方式,这与期望代码通过 `new Function` 运行的 `ssrFetchModule` 是不同的,这一点可以从这些函数返回的 sourcemap 中看出。
5555

56-
Runner in `ViteRuntime` is responsible for executing the code. Vite exports `ESModulesRunner` out of the box, it uses `new AsyncFunction` to run the code. You can provide your own implementation if your JavaScript runtime doesn't support unsafe evaluation.
56+
`ViteRuntime` 中的 Runner 负责执行代码。Vite 开箱即用地提供了 `ESModulesRunner`,它使用 `new AsyncFunction` 来运行代码。如果你的 JavaScript 运行环境不支持不安全的执行,你可以提供你自己的实现。
5757

58-
The two main methods that runtime exposes are `executeUrl` and `executeEntrypoint`. The only difference between them is that all modules executed by `executeEntrypoint` will be reexecuted if HMR triggers `full-reload` event. Be aware that Vite Runtime doesn't update `exports` object when this happens (it overrides it), you would need to run `executeUrl` or get the module from `moduleCache` again if you rely on having the latest `exports` object.
58+
运行时公开的两个主要方法是 `executeUrl` `executeEntrypoint`。它们之间唯一的区别是,如果热模块替换(HMR)触发了 `full-reload` 事件,那么 `executeEntrypoint` 执行的所有模块都将重新执行。但请注意,当这种情况发生时,Vite 运行时不会更新 `exports` 对象(它会被覆盖),如果你需要最新的 `exports` 对象,你需要重新运行 `executeUrl` 或从 `moduleCache` 再次获取模块。
5959

60-
**Example Usage:**
60+
**使用示例:**
6161

6262
```js
6363
import { ViteRuntime, ESModulesRunner } from 'vite/runtime'
@@ -67,7 +67,7 @@ const runtime = new ViteRuntime(
6767
{
6868
root,
6969
fetchModule,
70-
// you can also provide hmr.connection to support HMR
70+
// 你也可以提供 hmr.connection 以支持 HMR
7171
},
7272
new ESModulesRunner(),
7373
)
@@ -80,55 +80,55 @@ await runtime.executeEntrypoint('/src/entry-point.js')
8080
```ts
8181
export interface ViteRuntimeOptions {
8282
/**
83-
* Root of the project
83+
* 项目根目录
8484
*/
8585
root: string
8686
/**
87-
* A method to get the information about the module.
88-
* For SSR, Vite exposes `server.ssrFetchModule` function that you can use here.
89-
* For other runtime use cases, Vite also exposes `fetchModule` from its main entry point.
87+
* 获取模块信息的方法
88+
* 对于 SSRVite 提供了你可以使用的 `server.ssrFetchModule` 函数。
89+
* 对于其他运行时用例,Vite 也从其主入口点提供了 `fetchModule`
9090
*/
9191
fetchModule: FetchFunction
9292
/**
93-
* Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available.
94-
* Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method.
95-
* You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite.
93+
* 配置 sourcemap 的解析方式。如果 `process.setSourceMapsEnabled` 可用,优先选择 `node`。
94+
* 否则,默认使用 `prepareStackTrace`,这会覆盖 `Error.prepareStackTrace` 方法。
95+
* 你可以提供一个对象来配置如何解析那些没有被 Vite 处理过的文件的内容和源代码映射。
9696
*/
9797
sourcemapInterceptor?:
9898
| false
9999
| 'node'
100100
| 'prepareStackTrace'
101101
| InterceptorOptions
102102
/**
103-
* Disable HMR or configure HMR options.
103+
* 禁用 HMR 或配置 HMR 选项。
104104
*/
105105
hmr?:
106106
| false
107107
| {
108108
/**
109-
* Configure how HMR communicates between the client and the server.
109+
* 配置 HMR 如何在客户端和服务器之间通信。
110110
*/
111111
connection: HMRRuntimeConnection
112112
/**
113-
* Configure HMR logger.
113+
* 配置 HMR 日志。
114114
*/
115115
logger?: false | HMRLogger
116116
}
117117
/**
118-
* Custom module cache. If not provided, it creates a separate module cache for each ViteRuntime instance.
118+
* 自定义模块缓存。如果未提供,它将为每个 Vite 运行环境实例创建一个独立的模块缓存。
119119
*/
120120
moduleCache?: ModuleCacheMap
121121
}
122122
```
123123

124124
## `ViteModuleRunner`
125125

126-
**Type Signature:**
126+
**类型签名:**
127127

128128
```ts
129129
export interface ViteModuleRunner {
130130
/**
131-
* Run code that was transformed by Vite.
131+
* 运行被 Vite 转换过的代码。
132132
* @param context Function context
133133
* @param code Transformed code
134134
* @param id ID that was used to fetch the module
@@ -139,52 +139,52 @@ export interface ViteModuleRunner {
139139
id: string,
140140
): Promise<any>
141141
/**
142-
* Run externalized module.
142+
* 运行已外部化的模块。
143143
* @param file File URL to the external module
144144
*/
145145
runExternalModule(file: string): Promise<any>
146146
}
147147
```
148148

149-
Vite exports `ESModulesRunner` that implements this interface by default. It uses `new AsyncFunction` to run code, so if the code has inlined source map it should contain an [offset of 2 lines](https://tc39.es/ecma262/#sec-createdynamicfunction) to accommodate for new lines added. This is done automatically by `server.ssrFetchModule`. If your runner implementation doesn't have this constraint, you should use `fetchModule` (exported from `vite`) directly.
149+
Vite 默认导出了实现了这个接口的 `ESModulesRunner`。它使用 `new AsyncFunction` 来执行代码,所以如果代码中有内联的源代码映射(sourcemap),它应该包含 [2行的偏移](https://tc39.es/ecma262/#sec-createdynamicfunction) 以适应新添加的行。这是由 `server.ssrFetchModule` 自动完成的。如果你的 runner 实现没有这个限制,你应该直接使用 `fetchModule`(从 `vite` 导出)。
150150

151151
## HMRRuntimeConnection
152152

153-
**Type Signature:**
153+
**类型签名:**
154154

155155
```ts
156156
export interface HMRRuntimeConnection {
157157
/**
158-
* Checked before sending messages to the client.
158+
* 在向客户端发送消息之前进行检查
159159
*/
160160
isReady(): boolean
161161
/**
162-
* Send message to the client.
162+
* 向客户端发送消息
163163
*/
164164
send(message: string): void
165165
/**
166-
* Configure how HMR is handled when this connection triggers an update.
167-
* This method expects that connection will start listening for HMR updates and call this callback when it's received.
166+
* 配置当此连接触发更新时如何处理 HMR
167+
* 此方法期望连接将开始监听 HMR 更新,并在接收到时调用此回调。
168168
*/
169169
onUpdate(callback: (payload: HMRPayload) => void): void
170170
}
171171
```
172172

173-
This interface defines how HMR communication is established. Vite exports `ServerHMRConnector` from the main entry point to support HMR during Vite SSR. The `isReady` and `send` methods are usually called when the custom event is triggered (like, `import.meta.hot.send("my-event")`).
173+
这个接口定义了如何建立热模块替换(HMR)的通信。Vite 从主入口处导出 `ServerHMRConnector`,以在 Vite SSR 期间支持 HMR。当自定义事件被触发时(例如,`import.meta.hot.send("my-event")`),通常会调用 `isReady``send` 方法。
174174

175-
`onUpdate` is called only once when the new runtime is initiated. It passed down a method that should be called when connection triggers the HMR event. The implementation depends on the type of connection (as an example, it can be `WebSocket`/`EventEmitter`/`MessageChannel`), but it usually looks something like this:
175+
只有在新的运行环境启动时,才会调用 `onUpdate`。它传递下来一个在连接触发 HMR 事件时应该调用的方法。实现方式取决于连接的类型(例如,它可以是 `WebSocket`/`EventEmitter`/`MessageChannel`),但通常看起来像这样:
176176

177177
```js
178178
function onUpdate(callback) {
179179
this.connection.on('hmr', (event) => callback(event.data))
180180
}
181181
```
182182

183-
The callback is queued and it will wait for the current update to be resolved before processing the next update. Unlike the browser implementation, HMR updates in Vite Runtime wait until all listeners (like, `vite:beforeUpdate`/`vite:beforeFullReload`) are finished before updating the modules.
183+
回调会被放入队列中,它会等待当前的更新完成后才处理下一个更新。与浏览器的实现不同,Vite 运行环境中的 HMR 更新会等到所有的监听器(例如,`vite:beforeUpdate`/`vite:beforeFullReload`)都完成后才更新模块。
184184

185185
## `createViteRuntime`
186186

187-
**Type Signature:**
187+
**类型签名:**
188188

189189
```ts
190190
async function createViteRuntime(
@@ -193,7 +193,7 @@ async function createViteRuntime(
193193
): Promise<ViteRuntime>
194194
```
195195

196-
**Example Usage:**
196+
**使用示例:**
197197

198198
```js
199199
import { createServer } from 'vite'
@@ -211,23 +211,23 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url))
211211
})()
212212
```
213213

214-
This method serves as an easy replacement for `server.ssrLoadModule`. Unlike `ssrLoadModule`, `createViteRuntime` provides HMR support out of the box. You can pass down [`options`](#mainthreadruntimeoptions) to customize how SSR runtime behaves to suit your needs.
214+
这个方法可以作为 `server.ssrLoadModule` 的简单替代。不同于 `ssrLoadModule``createViteRuntime` 默认就支持 HMR。你可以传递 [`options`](#mainthreadruntimeoptions) 来定制 SSR 运行环境的行为,以满足你的需求。
215215

216216
## `MainThreadRuntimeOptions`
217217

218218
```ts
219219
export interface MainThreadRuntimeOptions
220220
extends Omit<ViteRuntimeOptions, 'root' | 'fetchModule' | 'hmr'> {
221221
/**
222-
* Disable HMR or configure HMR logger.
222+
* 禁用 HMR 或配置 HMR 日志。
223223
*/
224224
hmr?:
225225
| false
226226
| {
227227
logger?: false | HMRLogger
228228
}
229229
/**
230-
* Provide a custom module runner. This controls how the code is executed.
230+
* 提供自定义模块运行器。这决定了代码的执行方式。
231231
*/
232232
runner?: ViteModuleRunner
233233
}

0 commit comments

Comments
 (0)