フレームワーク向け環境 API
実験的
環境 API は実験的です。エコシステムが実験し、その上に構築できるように、Vite 6 では API を安定させます。Vite 7 では、破壊的変更の可能性があるこれらの新しい API を安定させる予定です。
リソース
- 新しい API に関するフィードバックを収集しているフィードバックに関する議論。
- 新しい API が実装され、レビューされた環境 API のプルリクエスト。
フィードバックをお寄せください。
環境とフレームワーク
暗黙的な `ssr` 環境とその他の非クライアント環境は、開発中はデフォルトで `RunnableDevEnvironment` を使用します。これはランタイムが Vite サーバーを実行しているランタイムと同じであることを要求しますが、これは `ssrLoadModule` と同様に機能し、フレームワークが SSR 開発ストーリーの移行と HMR の有効化を可能にします。`isRunnableDevEnvironment` 関数を使用して、実行可能な環境をガードできます。
export class RunnableDevEnvironment extends DevEnvironment {
public readonly runner: ModuleRunner
}
class ModuleRunner {
/**
* URL to execute.
* Accepts file path, server path, or id relative to the root.
* Returns an instantiated module (same as in ssrLoadModule)
*/
public async import(url: string): Promise<Record<string, any>>
/**
* Other ModuleRunner methods...
*/
}
if (isRunnableDevEnvironment(server.environments.ssr)) {
await server.environments.ssr.runner.import('/entry-point.js')
}
警告
`runner` は、初めてアクセスされたときに積極的に評価されます。Vite は、`process.setSourceMapsEnabled` を呼び出すか、利用できない場合は `Error.prepareStackTrace` をオーバーライドすることで、`runner` が作成されたときにソースマップのサポートを有効にすることに注意してください。
デフォルトの `RunnableDevEnvironment`
SSR セットアップガイドで説明されているように、ミドルウェアモードで構成された Vite サーバーを考えると、環境 API を使用して SSR ミドルウェアを実装してみましょう。エラー処理は省略されています。
import { createServer } from 'vite'
const server = await createServer({
server: { middlewareMode: true },
appType: 'custom',
environments: {
server: {
// by default, modules are run in the same process as the vite server
},
},
})
// You might need to cast this to RunnableDevEnvironment in TypeScript or
// use isRunnableDevEnvironment to guard the access to the runner
const environment = server.environments.node
app.use('*', async (req, res, next) => {
const url = req.originalUrl
// 1. Read index.html
const indexHtmlPath = path.resolve(__dirname, 'index.html')
let template = fs.readFileSync(indexHtmlPath, 'utf-8')
// 2. Apply Vite HTML transforms. This injects the Vite HMR client,
// and also applies HTML transforms from Vite plugins, e.g. global
// preambles from @vitejs/plugin-react
template = await server.transformIndexHtml(url, template)
// 3. Load the server entry. import(url) automatically transforms
// ESM source code to be usable in Node.js! There is no bundling
// required, and provides full HMR support.
const { render } = await environment.runner.import('/src/entry-server.js')
// 4. render the app HTML. This assumes entry-server.js's exported
// `render` function calls appropriate framework SSR APIs,
// e.g. ReactDOMServer.renderToString()
const appHtml = await render(url)
// 5. Inject the app-rendered HTML into the template.
const html = template.replace(`<!--ssr-outlet-->`, appHtml)
// 6. Send the rendered HTML back.
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
})
ランタイムに依存しない SSR
`RunnableDevEnvironment` は Vite サーバーと同じランタイムでコードを実行するためにのみ使用できるため、Vite サーバーを実行できるランタイム (Node.js と互換性のあるランタイム) が必要です。これは、ランタイムに依存しないようにするには、生の `DevEnvironment` を使用する必要があることを意味します。
`FetchableDevEnvironment` 提案
最初の提案では、`DevEnvironment` クラスに `run` メソッドがあり、コンシューマーは `transport` オプションを使用してランナー側でインポートを呼び出すことができました。テスト中に、API が推奨を開始するのに十分に普遍的ではないことがわかりました。現時点では、`FetchableDevEnvironment` 提案に関するフィードバックを求めています。
`RunnableDevEnvironment` には、モジュールの値を返す `runner.import` 関数があります。ただし、この関数は生の `DevEnvironment` では使用できず、Vite の API を使用するコードとユーザーモジュールを分離する必要があります。
たとえば、次の例では、Vite の API を使用するコードからユーザーモジュールの値を使用しています
// code using the Vite's APIs
import { createServer } from 'vite'
const server = createServer()
const ssrEnvironment = server.environment.ssr
const input = {}
const { createHandler } = await ssrEnvironment.runner.import('./entry.js')
const handler = createHandler(input)
const response = handler(new Request('/'))
// -------------------------------------
// ./entrypoint.js
export function createHandler(input) {
return function handler(req) {
return new Response('hello')
}
}
コードがユーザーモジュールと同じランタイムで実行できる場合 (つまり、Node.js 固有の API に依存しない場合)、仮想モジュールを使用できます。このアプローチにより、Vite の API を使用するコードから値にアクセスする必要がなくなります。
// code using the Vite's APIs
import { createServer } from 'vite'
const server = createServer({
plugins: [
// a plugin that handles `virtual:entrypoint`
{
name: 'virtual-module',
/* plugin implementation */
},
],
})
const ssrEnvironment = server.environment.ssr
const input = {}
// use exposed functions by each environment factories that runs the code
// check for each environment factories what they provide
if (ssrEnvironment instanceof RunnableDevEnvironment) {
ssrEnvironment.runner.import('virtual:entrypoint')
} else if (ssrEnvironment instanceof CustomDevEnvironment) {
ssrEnvironment.runEntrypoint('virtual:entrypoint')
} else {
throw new Error(`Unsupported runtime for ${ssrEnvironment.name}`)
}
// -------------------------------------
// virtual:entrypoint
const { createHandler } = await import('./entrypoint.js')
const handler = createHandler(input)
const response = handler(new Request('/'))
// -------------------------------------
// ./entrypoint.js
export function createHandler(input) {
return function handler(req) {
return new Response('hello')
}
}
たとえば、ユーザーモジュールで `transformIndexHtml` を呼び出すには、次のプラグインを使用できます
function vitePluginVirtualIndexHtml(): Plugin {
let server: ViteDevServer | undefined
return {
name: vitePluginVirtualIndexHtml.name,
configureServer(server_) {
server = server_
},
resolveId(source) {
return source === 'virtual:index-html' ? '\0' + source : undefined
},
async load(id) {
if (id === '\0' + 'virtual:index-html') {
let html: string
if (server) {
this.addWatchFile('index.html')
html = fs.readFileSync('index.html', 'utf-8')
html = await server.transformIndexHtml('/', html)
} else {
html = fs.readFileSync('dist/client/index.html', 'utf-8')
}
return `export default ${JSON.stringify(html)}`
}
return
},
}
}
コードで Node.js API が必要な場合は、`hot.send` を使用して、ユーザーモジュールから Vite の API を使用するコードと通信できます。ただし、このアプローチはビルドプロセス後には同じようには機能しない可能性があることに注意してください。
// code using the Vite's APIs
import { createServer } from 'vite'
const server = createServer({
plugins: [
// a plugin that handles `virtual:entrypoint`
{
name: 'virtual-module',
/* plugin implementation */
},
],
})
const ssrEnvironment = server.environment.ssr
const input = {}
// use exposed functions by each environment factories that runs the code
// check for each environment factories what they provide
if (ssrEnvironment instanceof RunnableDevEnvironment) {
ssrEnvironment.runner.import('virtual:entrypoint')
} else if (ssrEnvironment instanceof CustomDevEnvironment) {
ssrEnvironment.runEntrypoint('virtual:entrypoint')
} else {
throw new Error(`Unsupported runtime for ${ssrEnvironment.name}`)
}
const req = new Request('/')
const uniqueId = 'a-unique-id'
ssrEnvironment.send('request', serialize({ req, uniqueId }))
const response = await new Promise((resolve) => {
ssrEnvironment.on('response', (data) => {
data = deserialize(data)
if (data.uniqueId === uniqueId) {
resolve(data.res)
}
})
})
// -------------------------------------
// virtual:entrypoint
const { createHandler } = await import('./entrypoint.js')
const handler = createHandler(input)
import.meta.hot.on('request', (data) => {
const { req, uniqueId } = deserialize(data)
const res = handler(req)
import.meta.hot.send('response', serialize({ res: res, uniqueId }))
})
const response = handler(new Request('/'))
// -------------------------------------
// ./entrypoint.js
export function createHandler(input) {
return function handler(req) {
return new Response('hello')
}
}
ビルド中の環境
CLI では、`vite build` と `vite build --ssr` を呼び出すと、下位互換性のためにクライアントのみと ssr のみの環境がビルドされます。
`builder` が `undefined` でない場合 (または `vite build --app` を呼び出す場合)、`vite build` は代わりにアプリ全体のビルドをオプトインします。これは、将来のメジャーバージョンではデフォルトになります。`ViteBuilder` インスタンスが作成され (ビルド時の `ViteDevServer` に相当)、本番環境向けに構成されたすべての環境がビルドされます。デフォルトでは、環境のビルドは `environments` レコードの順序を尊重して順番に実行されます。フレームワークまたはユーザーは、次を使用して環境のビルド方法をさらに構成できます
export default {
builder: {
buildApp: async (builder) => {
const environments = Object.values(builder.environments)
return Promise.all(
environments.map((environment) => builder.build(environment)),
)
},
},
}
環境に依存しないコード
ほとんどの場合、現在の `environment` インスタンスは実行されているコードのコンテキストの一部として利用できるため、`server.environments` を介してアクセスする必要はまれです。たとえば、プラグインフック内では、環境は `PluginContext` の一部として公開されるため、`this.environment` を使用してアクセスできます。環境対応プラグインの構築方法については、プラグイン向け環境 API を参照してください。