-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: experimental Vite Runtime API #12165
Merged
Merged
Changes from all commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
3ba7436
feat: add vite-node into the core
sheremet-va c0de2ff
fix: normalize entry url before calling fetchModule
sheremet-va 2423810
refactor: expose more types, fix caching with the query issue, requir…
sheremet-va a91fc5a
chore: export HMRRuntimeConnection
sheremet-va 8f4b6d1
refactor: remove cleanup function from onUpdate
sheremet-va 090246e
refactor: remove processImport from the public API
sheremet-va 95434b4
test: add test for HMR on files imported with queries
sheremet-va a6fd97b
feat: support source map
sheremet-va 1475aeb
chore: add check for types chunk
sheremet-va f83f0e3
test: remove only
sheremet-va 3205c54
chore: change default to use node interceptor if available
sheremet-va d8fce47
refactor: expose "fetchModule" via a "vite" entypoint, improve types
sheremet-va 2949d96
fix: allow several runtimes to influece source maps
sheremet-va bcfe993
fix: externalize network urls by default
sheremet-va aa5354e
chore: cleanup
sheremet-va db80f51
Merge branch 'main' into feat/vite-node-core
sheremet-va 3f044b0
chore: cleanup
sheremet-va 0b31ff7
refactor: add more jsdocs to vite runtime, add isDestroyed
sheremet-va 84283ff
docs: add documentation about vite runtime
sheremet-va 0e0263e
chore: typo
patak-dev ff81b02
chore: typo
patak-dev fb46227
chore: typo
patak-dev bab1559
chore: wording
patak-dev 34f2363
chore: wording
patak-dev c58fbe0
chore: typo
patak-dev cf38151
chore: typo
patak-dev 9764b51
chore: warning about potential changes in Vite 5.2
patak-dev 3e18bb7
chore: wording
patak-dev 294a50a
test: correct hmr ports
sheremet-va fea94b5
test: fix ports
sheremet-va 0573c0d
chore: review feedback
sheremet-va 4c0d3fa
docs: add experimental jsdoc to runtime APIs available from "vite" en…
sheremet-va 1db9c01
refactor: update source map folder name
sheremet-va f7c3c25
chore: add a link to the discussion in runtime docs
sheremet-va File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,234 @@ | ||
# 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. | ||
::: | ||
|
||
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. | ||
|
||
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. | ||
|
||
All APIs can be imported from `vite/runtime` unless stated otherwise. | ||
|
||
## `ViteRuntime` | ||
|
||
**Type Signature:** | ||
|
||
```ts | ||
export class ViteRuntime { | ||
constructor( | ||
public options: ViteRuntimeOptions, | ||
public runner: ViteModuleRunner, | ||
private debug?: ViteRuntimeDebugger, | ||
) {} | ||
/** | ||
* URL to execute. Accepts file path, server path, or id relative to the root. | ||
*/ | ||
public async executeUrl<T = any>(url: string): Promise<T> | ||
/** | ||
* 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. | ||
*/ | ||
public async executeEntrypoint<T = any>(url: string): Promise<T> | ||
/** | ||
* Clear all caches including HMR listeners. | ||
*/ | ||
public clearCache(): void | ||
/** | ||
* Clears all caches, removes all HMR listeners, and resets source map support. | ||
* This method doesn't stop the HMR connection. | ||
*/ | ||
public async destroy(): Promise<void> | ||
/** | ||
* Returns `true` if the runtime has been destroyed by calling `destroy()` method. | ||
*/ | ||
public isDestroyed(): boolean | ||
} | ||
``` | ||
|
||
::: tip Advanced Usage | ||
If you are just migrating from `server.ssrLoadModule` and want to support HMR, consider using [`createViteRuntime`](#createviteruntime) instead. | ||
::: | ||
|
||
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. | ||
|
||
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. | ||
|
||
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. | ||
|
||
**Example Usage:** | ||
|
||
```js | ||
import { ViteRuntime, ESModulesRunner } from 'vite/runtime' | ||
import { root, fetchModule } from './rpc-implementation.js' | ||
|
||
const runtime = new ViteRuntime( | ||
{ | ||
root, | ||
fetchModule, | ||
// you can also provide hmr.connection to support HMR | ||
}, | ||
new ESModulesRunner(), | ||
) | ||
|
||
await runtime.executeEntrypoint('/src/entry-point.js') | ||
``` | ||
|
||
## `ViteRuntimeOptions` | ||
|
||
```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. | ||
*/ | ||
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. | ||
*/ | ||
sourcemapInterceptor?: | ||
| false | ||
| 'node' | ||
| 'prepareStackTrace' | ||
| InterceptorOptions | ||
/** | ||
* Disable HMR or configure HMR options. | ||
*/ | ||
hmr?: | ||
| false | ||
| { | ||
/** | ||
* Configure how HMR communicates between the client and the server. | ||
*/ | ||
connection: HMRRuntimeConnection | ||
/** | ||
* Configure HMR logger. | ||
*/ | ||
logger?: false | HMRLogger | ||
} | ||
/** | ||
* Custom module cache. If not provided, it creates a separate module cache for each ViteRuntime instance. | ||
*/ | ||
moduleCache?: ModuleCacheMap | ||
} | ||
``` | ||
|
||
## `ViteModuleRunner` | ||
|
||
**Type Signature:** | ||
|
||
```ts | ||
export interface ViteModuleRunner { | ||
/** | ||
* Run code that was transformed by Vite. | ||
* @param context Function context | ||
* @param code Transformed code | ||
* @param id ID that was used to fetch the module | ||
*/ | ||
runViteModule( | ||
context: ViteRuntimeModuleContext, | ||
code: string, | ||
id: string, | ||
): Promise<any> | ||
/** | ||
* Run externalized module. | ||
* @param file File URL to the external module | ||
*/ | ||
runExternalModule(file: string): Promise<any> | ||
} | ||
``` | ||
|
||
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. | ||
|
||
## 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. | ||
*/ | ||
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")`). | ||
|
||
`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: | ||
|
||
```js | ||
function onUpdate(callback) { | ||
this.connection.on('hmr', (event) => callback(event.data)) | ||
} | ||
``` | ||
|
||
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. | ||
|
||
## `createViteRuntime` | ||
|
||
**Type Signature:** | ||
|
||
```ts | ||
async function createViteRuntime( | ||
server: ViteDevServer, | ||
options?: MainThreadRuntimeOptions, | ||
): Promise<ViteRuntime> | ||
``` | ||
|
||
**Example Usage:** | ||
|
||
```js | ||
import { createServer } from 'vite' | ||
|
||
const __dirname = fileURLToPath(new URL('.', import.meta.url)) | ||
|
||
;(async () => { | ||
const server = await createServer({ | ||
root: __dirname, | ||
}) | ||
await server.listen() | ||
|
||
const runtime = await createViteRuntime(server) | ||
await runtime.executeEntrypoint('/src/entry-point.js') | ||
})() | ||
``` | ||
|
||
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. | ||
|
||
## `MainThreadRuntimeOptions` | ||
|
||
```ts | ||
export interface MainThreadRuntimeOptions | ||
extends Omit<ViteRuntimeOptions, 'root' | 'fetchModule' | 'hmr'> { | ||
/** | ||
* Disable HMR or configure HMR logger. | ||
*/ | ||
hmr?: | ||
| false | ||
| { | ||
logger?: false | HMRLogger | ||
} | ||
/** | ||
* Provide a custom module runner. This controls how the code is executed. | ||
*/ | ||
runner?: ViteModuleRunner | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it will be helpful to have some links to custom implementations like @sapphi-red's one. At least during the experimental phase as it is a great resource to see the API in action.
We can add these links in another PR though, once https://github.com/sapphi-red/vite-envs/tree/use-vite-runtime is merged into main in vite-envs
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, sounds like a good idea.