Package Exports
- vite-node
- vite-node/client
- vite-node/server
- vite-node/utils
Readme
vite-node
Vite as Node runtime. The engine powers Vitest.
Features
- Out-of-box ESM & TypeScript support (possible for more with plugins)
- Top-level
await - Vite plugins, resolve, aliasing
- Respect
vite.config.ts - Shims for
__dirnameand__filenamein ESM - Access to native node modules like
fs,path, etc.
CLI Usage
Run JS/TS file on Node.js using Vite's resolvers and transformers.
npx vite-node index.tsOptions:
npx vite-node -hProgrammatic Usage
In Vite Node, the server and runner (client) are separated, so you can integrate them in different contexts (workers, cross-process, or remote) if needed. The demo below shows a simple example of having both (server and runner) running in the same context
import { createServer } from 'vite'
import { ViteNodeServer } from 'vite-node/server'
import { ViteNodeRunner } from 'vite-node/client'
// create vite server
const server = await createServer({
optimizeDeps: {
// It's recommended to disable deps optimization
disabled: true,
},
})
// this is need to initialize the plugins
await server.pluginContainer.buildStart({})
// create vite-node server
const node = new ViteNodeServer(server)
// create vite-node runner
const runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
// when having the server and runner in a different context,
// you will need to handle the communication between them
// and pass to this function
fetchModule(id) {
return node.fetchModule(id)
},
resolveId(id, importer) {
return node.resolveId(id, importer)
},
})
// execute the file
await runner.executeFile('./example.ts')
// close the vite server
await server.close()Credits
Based on @pi0's brilliant idea of having a Vite server as the on-demand transforming service for Nuxt's Vite SSR.
Thanks @brillout for kindly sharing this package name.
Sponsors
License
MIT License © 2021 Anthony Fu