diff --git a/guide/api-javascript.md b/guide/api-javascript.md index 159a1033..d614d791 100644 --- a/guide/api-javascript.md +++ b/guide/api-javascript.md @@ -1,6 +1,6 @@ # JavaScript API {#javascript-api} -Vite 的 JavaScript API 是完全类型化的,我们推荐使用 TypeScript 或者在 VS Code 中启用 JS 类型检查来利用智能提示和类型校验。 +Vite 的 JavaScript API 是完全类型化的,我们推荐使用 TypeScript 或者在 VS Code 中启用 JS 类型检查来利用智能提示和类型签名。 ## `createServer` {#createserver} @@ -186,7 +186,7 @@ interface ViteDevServer { ## `build` {#build} -**类型校验:** +**类型签名:** ```ts async function build( @@ -281,7 +281,7 @@ interface PreviewServer { ## `resolveConfig` {#resolveconfig} -**类型校验:** +**类型签名:** ```ts async function resolveConfig( diff --git a/guide/api-vite-runtime.md b/guide/api-vite-runtime.md index 5c4ee3f0..82773430 100644 --- a/guide/api-vite-runtime.md +++ b/guide/api-vite-runtime.md @@ -1,18 +1,18 @@ -# Vite Runtime API +# Vite 运行时 API {#vite-runtime-api} -:::warning Low-level API -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. +:::warning 低级别 API +这个 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 插件和工具。 ::: -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. +"Vite 运行时" 是一个工具,它允许首先用 Vite 插件处理任何代码后运行。它与 `server.ssrLoadModule` 不同,因为运行时实现是从服务器解耦的。这允许库和框架作者实现他们自己的服务器和运行时之间的通信层。 -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. +这个特性的一个目标是提供一个可定制的API来处理和运行代码。Vite 提供了足够的工具来开箱即用 Vite 运行时,但如果用户的需求与 Vite 的内置实现不一致,他们可以在其基础上进行构建。 -All APIs can be imported from `vite/runtime` unless stated otherwise. +除非另有说明,所有API都可以从 `vite/runtime` 导入。 ## `ViteRuntime` -**Type Signature:** +**类型签名:** ```ts export class ViteRuntime { @@ -22,42 +22,42 @@ export class ViteRuntime { private debug?: ViteRuntimeDebugger, ) {} /** - * URL to execute. Accepts file path, server path, or id relative to the root. + * 要执行的 URL。可以是文件路径、服务器路径,或者是相对于根目录的 id。 */ public async executeUrl(url: string): Promise /** - * Entry point URL to execute. Accepts file path, server path or id relative to the root. - * In the case of a full reload triggered by HMR, this is the module that will be reloaded. - * If this method is called multiple times, all entry points will be reloaded one at a time. + * 执行的入口文件 URL。可以是文件路径、服务器路径,或者是相对于根目录的 id。 + * 如果是由 HMR 触发的全面重载,那么这就是将要被重载的模块。 + * 如果这个方法被多次调用,所有的入口文件都将逐一被重新加载。 */ public async executeEntrypoint(url: string): Promise /** - * Clear all caches including HMR listeners. + * 清除所有缓存,包括 HMR 监听器。 */ public clearCache(): void /** - * Clears all caches, removes all HMR listeners, and resets source map support. - * This method doesn't stop the HMR connection. + * 清除所有缓存,移除所有 HMR 监听器,并重置 sourcemap 支持。 + * 此方法不会停止 HMR 连接。 */ public async destroy(): Promise /** - * Returns `true` if the runtime has been destroyed by calling `destroy()` method. + * 如果通过调用 `destroy()` 方法销毁了运行时,则返回 `true`。 */ public isDestroyed(): boolean } ``` -::: tip Advanced Usage -If you are just migrating from `server.ssrLoadModule` and want to support HMR, consider using [`createViteRuntime`](#createviteruntime) instead. +::: tip 进阶用法 +如果你是从 `server.ssrLoadModule` 迁移过来,并且想要支持热模块替换(HMR),你可以考虑用 [`createViteRuntime`](#createviteruntime) 替代。 ::: -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. +当你初始化 `ViteRuntime` 类时,需要 `root` 和 `fetchModule` 这两个选项。Vite 在 [`server`](/guide/api-javascript) 实例中公开了 `ssrFetchModule`,以便更方便地与 Vite SSR 集成。Vite 主入口也导出了 `fetchModule` - 它不会假设代码的运行方式,这与期望代码通过 `new Function` 运行的 `ssrFetchModule` 是不同的,这一点可以从这些函数返回的 sourcemap 中看出。 -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. +`ViteRuntime` 中的 Runner 负责执行代码。Vite 开箱即用地提供了 `ESModulesRunner`,它使用 `new AsyncFunction` 来运行代码。如果你的 JavaScript 运行环境不支持不安全的执行,你可以提供你自己的实现。 -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. +运行时公开的两个主要方法是 `executeUrl` 和 `executeEntrypoint`。它们之间唯一的区别是,如果热模块替换(HMR)触发了 `full-reload` 事件,那么 `executeEntrypoint` 执行的所有模块都将重新执行。但请注意,当这种情况发生时,Vite 运行时不会更新 `exports` 对象(它会被覆盖),如果你需要最新的 `exports` 对象,你需要重新运行 `executeUrl` 或从 `moduleCache` 再次获取模块。 -**Example Usage:** +**使用示例:** ```js import { ViteRuntime, ESModulesRunner } from 'vite/runtime' @@ -67,7 +67,7 @@ const runtime = new ViteRuntime( { root, fetchModule, - // you can also provide hmr.connection to support HMR + // 你也可以提供 hmr.connection 以支持 HMR。 }, new ESModulesRunner(), ) @@ -80,19 +80,19 @@ await runtime.executeEntrypoint('/src/entry-point.js') ```ts export interface ViteRuntimeOptions { /** - * Root of the project + * 项目根目录 */ root: string /** - * A method to get the information about the module. - * For SSR, Vite exposes `server.ssrFetchModule` function that you can use here. - * For other runtime use cases, Vite also exposes `fetchModule` from its main entry point. + * 获取模块信息的方法 + * 对于 SSR,Vite 提供了你可以使用的 `server.ssrFetchModule` 函数。 + * 对于其他运行时用例,Vite 也从其主入口点提供了 `fetchModule`。 */ fetchModule: FetchFunction /** - * Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available. - * Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method. - * You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite. + * 配置 sourcemap 的解析方式。如果 `process.setSourceMapsEnabled` 可用,优先选择 `node`。 + * 否则,默认使用 `prepareStackTrace`,这会覆盖 `Error.prepareStackTrace` 方法。 + * 你可以提供一个对象来配置如何解析那些没有被 Vite 处理过的文件的内容和源代码映射。 */ sourcemapInterceptor?: | false @@ -100,22 +100,22 @@ export interface ViteRuntimeOptions { | 'prepareStackTrace' | InterceptorOptions /** - * Disable HMR or configure HMR options. + * 禁用 HMR 或配置 HMR 选项。 */ hmr?: | false | { /** - * Configure how HMR communicates between the client and the server. + * 配置 HMR 如何在客户端和服务器之间通信。 */ connection: HMRRuntimeConnection /** - * Configure HMR logger. + * 配置 HMR 日志。 */ logger?: false | HMRLogger } /** - * Custom module cache. If not provided, it creates a separate module cache for each ViteRuntime instance. + * 自定义模块缓存。如果未提供,它将为每个 Vite 运行环境实例创建一个独立的模块缓存。 */ moduleCache?: ModuleCacheMap } @@ -123,12 +123,12 @@ export interface ViteRuntimeOptions { ## `ViteModuleRunner` -**Type Signature:** +**类型签名:** ```ts export interface ViteModuleRunner { /** - * Run code that was transformed by Vite. + * 运行被 Vite 转换过的代码。 * @param context Function context * @param code Transformed code * @param id ID that was used to fetch the module @@ -139,40 +139,40 @@ export interface ViteModuleRunner { id: string, ): Promise /** - * Run externalized module. + * 运行已外部化的模块。 * @param file File URL to the external module */ runExternalModule(file: string): Promise } ``` -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. +Vite 默认导出了实现了这个接口的 `ESModulesRunner`。它使用 `new AsyncFunction` 来执行代码,所以如果代码中有内联的源代码映射(sourcemap),它应该包含 [2行的偏移](https://tc39.es/ecma262/#sec-createdynamicfunction) 以适应新添加的行。这是由 `server.ssrFetchModule` 自动完成的。如果你的 runner 实现没有这个限制,你应该直接使用 `fetchModule`(从 `vite` 导出)。 ## HMRRuntimeConnection -**Type Signature:** +**类型签名:** ```ts export interface HMRRuntimeConnection { /** - * Checked before sending messages to the client. + * 在向客户端发送消息之前进行检查 */ isReady(): boolean /** - * Send message to the client. + * 向客户端发送消息 */ send(message: string): void /** - * Configure how HMR is handled when this connection triggers an update. - * This method expects that connection will start listening for HMR updates and call this callback when it's received. + * 配置当此连接触发更新时如何处理 HMR。 + * 此方法期望连接将开始监听 HMR 更新,并在接收到时调用此回调。 */ onUpdate(callback: (payload: HMRPayload) => void): void } ``` -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")`). +这个接口定义了如何建立热模块替换(HMR)的通信。Vite 从主入口处导出 `ServerHMRConnector`,以在 Vite SSR 期间支持 HMR。当自定义事件被触发时(例如,`import.meta.hot.send("my-event")`),通常会调用 `isReady` 和 `send` 方法。 -`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: +只有在新的运行环境启动时,才会调用 `onUpdate`。它传递下来一个在连接触发 HMR 事件时应该调用的方法。实现方式取决于连接的类型(例如,它可以是 `WebSocket`/`EventEmitter`/`MessageChannel`),但通常看起来像这样: ```js function onUpdate(callback) { @@ -180,11 +180,11 @@ function onUpdate(callback) { } ``` -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. +回调会被放入队列中,它会等待当前的更新完成后才处理下一个更新。与浏览器的实现不同,Vite 运行环境中的 HMR 更新会等到所有的监听器(例如,`vite:beforeUpdate`/`vite:beforeFullReload`)都完成后才更新模块。 ## `createViteRuntime` -**Type Signature:** +**类型签名:** ```ts async function createViteRuntime( @@ -193,7 +193,7 @@ async function createViteRuntime( ): Promise ``` -**Example Usage:** +**使用示例:** ```js import { createServer } from 'vite' @@ -211,7 +211,7 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url)) })() ``` -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. +这个方法可以作为 `server.ssrLoadModule` 的简单替代。不同于 `ssrLoadModule`,`createViteRuntime` 默认就支持 HMR。你可以传递 [`options`](#mainthreadruntimeoptions) 来定制 SSR 运行环境的行为,以满足你的需求。 ## `MainThreadRuntimeOptions` @@ -219,7 +219,7 @@ This method serves as an easy replacement for `server.ssrLoadModule`. Unlike `ss export interface MainThreadRuntimeOptions extends Omit { /** - * Disable HMR or configure HMR logger. + * 禁用 HMR 或配置 HMR 日志。 */ hmr?: | false @@ -227,7 +227,7 @@ export interface MainThreadRuntimeOptions logger?: false | HMRLogger } /** - * Provide a custom module runner. This controls how the code is executed. + * 提供自定义模块运行器。这决定了代码的执行方式。 */ runner?: ViteModuleRunner }