Runtimes 用の環境 API
実験的機能
環境 API は実験的です。エコシステムが実験し、それらを基盤として構築できるように、メジャーリリース間での API の安定性は引き続き維持されます。ダウンストリームプロジェクトが新機能を実験し、検証する時間を持った後、将来のメジャーリリースでこれらの新しい API を安定化させる予定です(潜在的な破壊的変更を伴う可能性があります)。
リソース
- フィードバックディスカッション (新しい API に関するフィードバックを収集しています)
- 環境 API PR (新しい API が実装され、レビューされた場所)
ぜひフィードバックをお寄せください。
環境ファクトリ
環境ファクトリは、Cloudflare のような環境プロバイダーによって実装されることを意図しており、エンドユーザーによる実装は意図されていません。環境ファクトリは、開発環境とビルド環境の両方でターゲットランタイムを使用する最も一般的なケースのための EnvironmentOptions を返します。デフォルトの環境オプションも設定できるため、ユーザーが設定する必要はありません。
function createWorkerdEnvironment(
userConfig: EnvironmentOptions,
): EnvironmentOptions {
return mergeConfig(
{
resolve: {
conditions: [
/*...*/
],
},
dev: {
createEnvironment(name, config) {
return createWorkerdDevEnvironment(name, config, {
hot: true,
transport: customHotChannel(),
})
},
},
build: {
createEnvironment(name, config) {
return createWorkerdBuildEnvironment(name, config)
},
},
},
userConfig,
)
}すると、設定ファイルは次のように書くことができます。
import { createWorkerdEnvironment } from 'vite-environment-workerd'
export default {
environments: {
ssr: createWorkerdEnvironment({
build: {
outDir: '/dist/ssr',
},
}),
rsc: createWorkerdEnvironment({
build: {
outDir: '/dist/rsc',
},
}),
},
}フレームワークは、workerd ランタイムを持つ環境を使用して、次のように SSR を実行できます。
const ssrEnvironment = server.environments.ssr新しい環境ファクトリの作成
Vite 開発サーバーは、デフォルトで client 環境と ssr 環境の2つの環境を公開します。クライアント環境はデフォルトでブラウザ環境であり、モジュールランナーは仮想モジュール /@vite/client をクライアントアプリにインポートすることで実装されます。SSR 環境はデフォルトで Vite サーバーと同じ Node ランタイムで実行され、HMR を完全にサポートした開発中にリクエストをレンダリングするためにアプリケーションサーバーを使用できます。
変換されたソースコードはモジュールと呼ばれ、各環境で処理されるモジュール間の関係はモジュールグラフに保持されます。これらのモジュールの変換されたコードは、実行のために各環境に関連付けられたランタイムに送信されます。モジュールがランタイムで評価されると、インポートされたモジュールが要求され、モジュールグラフのセクションの処理がトリガーされます。
Vite モジュールランナーは、Vite プラグインで最初に処理することで任意のコードを実行できます。これは、ランナーの実装がサーバーから分離されているため、server.ssrLoadModule とは異なります。これにより、ライブラリやフレームワークの作者は、Vite サーバーとランナー間の通信レイヤーを実装できます。ブラウザは、サーバーの Web Socket と HTTP リクエストを介して、対応する環境と通信します。Node モジュールランナーは、同じプロセスで実行されているため、モジュールを直接関数呼び出しで処理できます。他の環境は、workerd のような JS ランタイムや、Vitest が行うような Worker スレッドに接続してモジュールを実行できます。
この機能の目標の1つは、コードを処理および実行するためのカスタマイズ可能な API を提供することです。ユーザーは、公開されているプリミティブを使用して新しい環境ファクトリを作成できます。
import { DevEnvironment, HotChannel } from 'vite'
function createWorkerdDevEnvironment(
name: string,
config: ResolvedConfig,
context: DevEnvironmentContext
) {
const connection = /* ... */
const transport: HotChannel = {
on: (listener) => { connection.on('message', listener) },
send: (data) => connection.send(data),
}
const workerdDevEnvironment = new DevEnvironment(name, config, {
options: {
resolve: { conditions: ['custom'] },
...context.options,
},
hot: true,
transport,
})
return workerdDevEnvironment
}ModuleRunner
モジュールランナーはターゲットランタイムでインスタンス化されます。特に明記されていない限り、次のセクションのすべての API は vite/module-runner からインポートされます。このエクスポートエントリポイントは、モジュールランナーを作成するために必要な最小限のもののみをエクスポートするよう、可能な限り軽量に保たれています。
型シグネチャ
export class ModuleRunner {
constructor(
public options: ModuleRunnerOptions,
public evaluator: ModuleEvaluator = new ESModulesEvaluator(),
private debug?: ModuleRunnerDebugger,
) {}
/**
* URL to execute.
* Accepts file path, server path, or id relative to the root.
*/
public async import<T = any>(url: string): Promise<T>
/**
* Clear all caches including HMR listeners.
*/
public clearCache(): void
/**
* Clear all caches, remove all HMR listeners, reset sourcemap support.
* This method doesn't stop the HMR connection.
*/
public async close(): Promise<void>
/**
* Returns `true` if the runner has been closed by calling `close()`.
*/
public isClosed(): boolean
}ModuleRunner のモジュールエバリュエーターは、コードの実行を担当します。Vite は ESModulesEvaluator をすぐにエクスポートし、new AsyncFunction を使用してコードを評価します。JavaScript ランタイムが安全でない評価をサポートしていない場合は、独自のカスタム実装を提供できます。
モジュールランナーは import メソッドを公開します。Vite サーバーが full-reload HMR イベントをトリガーすると、影響を受けるすべてのモジュールが再実行されます。このとき、モジュールランナーは exports オブジェクトを更新しない(上書きする)ことに注意してください。最新の exports オブジェクトに依存している場合は、import を実行するか、evaluatedModules からモジュールを再度取得する必要があります。
使用例
import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner'
import { transport } from './rpc-implementation.js'
const moduleRunner = new ModuleRunner(
{
transport,
},
new ESModulesEvaluator(),
)
await moduleRunner.import('/src/entry-point.js')ModuleRunnerOptions
interface ModuleRunnerOptions {
/**
* A set of methods to communicate with the server.
*/
transport: ModuleRunnerTransport
/**
* 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.
*/
sourcemapInterceptor?:
| false
| 'node'
| 'prepareStackTrace'
| InterceptorOptions
/**
* Disable HMR or configure HMR options.
*
* @default true
*/
hmr?: boolean | ModuleRunnerHmr
/**
* Custom module cache. If not provided, it creates a separate module
* cache for each module runner instance.
*/
evaluatedModules?: EvaluatedModules
}ModuleEvaluator
型シグネチャ
export interface ModuleEvaluator {
/**
* Number of prefixed lines in the transformed code.
*/
startOffset?: number
/**
* Evaluate code that was transformed by Vite.
* @param context Function context
* @param code Transformed code
* @param id ID that was used to fetch the module
*/
runInlinedModule(
context: ModuleRunnerContext,
code: string,
id: string,
): Promise<any>
/**
* evaluate externalized module.
* @param file File URL to the external module
*/
runExternalModule(file: string): Promise<any>
}Vite はデフォルトでこのインターフェースを実装する ESModulesEvaluator をエクスポートします。これは new AsyncFunction を使用してコードを評価するため、コードにインラインソースマップが含まれている場合、追加された改行に対応するために 2行のオフセット を含める必要があります。これは ESModulesEvaluator によって自動的に行われます。カスタムエバリュエーターは追加の行を追加しません。
ModuleRunnerTransport
型シグネチャ
interface ModuleRunnerTransport {
connect?(handlers: ModuleRunnerTransportHandlers): Promise<void> | void
disconnect?(): Promise<void> | void
send?(data: HotPayload): Promise<void> | void
invoke?(data: HotPayload): Promise<{ result: any } | { error: any }>
timeout?: number
}RPC または関数を直接呼び出すことで環境と通信するトランスポートオブジェクト。invoke メソッドが実装されていない場合、send メソッドと connect メソッドの実装が必要です。Vite は内部的に invoke を構築します。
モジュールランナーがワーカー・スレッドで作成されるこの例のように、サーバー上の HotChannel インスタンスと連携させる必要があります。
import { parentPort } from 'node:worker_threads'
import { fileURLToPath } from 'node:url'
import { ESModulesEvaluator, ModuleRunner } from 'vite/module-runner'
/** @type {import('vite/module-runner').ModuleRunnerTransport} */
const transport = {
connect({ onMessage, onDisconnection }) {
parentPort.on('message', onMessage)
parentPort.on('close', onDisconnection)
},
send(data) {
parentPort.postMessage(data)
},
}
const runner = new ModuleRunner(
{
transport,
},
new ESModulesEvaluator(),
)import { BroadcastChannel } from 'node:worker_threads'
import { createServer, RemoteEnvironmentTransport, DevEnvironment } from 'vite'
function createWorkerEnvironment(name, config, context) {
const worker = new Worker('./worker.js')
const handlerToWorkerListener = new WeakMap()
const workerHotChannel = {
send: (data) => worker.postMessage(data),
on: (event, handler) => {
if (event === 'connection') return
const listener = (value) => {
if (value.type === 'custom' && value.event === event) {
const client = {
send(payload) {
worker.postMessage(payload)
},
}
handler(value.data, client)
}
}
handlerToWorkerListener.set(handler, listener)
worker.on('message', listener)
},
off: (event, handler) => {
if (event === 'connection') return
const listener = handlerToWorkerListener.get(handler)
if (listener) {
worker.off('message', listener)
handlerToWorkerListener.delete(handler)
}
},
}
return new DevEnvironment(name, config, {
transport: workerHotChannel,
})
}
await createServer({
environments: {
worker: {
dev: {
createEnvironment: createWorkerEnvironment,
},
},
},
})ランナーとサーバー間の通信に HTTP リクエストを使用する別の例
import { ESModulesEvaluator, ModuleRunner } from 'vite/module-runner'
export const runner = new ModuleRunner(
{
transport: {
async invoke(data) {
const response = await fetch(`http://my-vite-server/invoke`, {
method: 'POST',
body: JSON.stringify(data),
})
return response.json()
},
},
hmr: false, // disable HMR as HMR requires transport.connect
},
new ESModulesEvaluator(),
)
await runner.import('/entry.js')この場合、NormalizedHotChannel の handleInvoke メソッドを使用できます。
const customEnvironment = new DevEnvironment(name, config, context)
server.onRequest((request: Request) => {
const url = new URL(request.url)
if (url.pathname === '/invoke') {
const payload = (await request.json()) as HotPayload
const result = customEnvironment.hot.handleInvoke(payload)
return new Response(JSON.stringify(result))
}
return Response.error()
})ただし、HMR をサポートするには、send メソッドと connect メソッドが必要です。send メソッドは通常、カスタムイベントがトリガーされたときに呼び出されます(例:import.meta.hot.send("my-event"))。
Vite は、Vite SSR 中の HMR をサポートするために、メインのエントリポイントから createServerHotChannel をエクスポートします。