Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

undefined

Vite Plugin Node


A vite plugin to allow you to use vite as node dev server.


Features


All the perks from Vite plus:
Node server HMR! (hot module replacement)
Support Express, Fastify, Koa and Nest out of the box
Support Custom Request Adapter
You can choose to use esbuild or swc to compile your typescript files

Get started


Install vite and this plugin with your favorite package manager, here use npm as example:

  1. ``` shell
  2. npm install vite vite-plugin-node -D
  3. ```

Create a vite.config.ts file in your project root to config vite to actually use this plugin:

  1. ``` ts
  2. import { defineConfig } from 'vite';
  3. import { VitePluginNode } from 'vite-plugin-node';

  4. export default defineConfig({
  5.   // ...vite configures
  6.   server: {
  7.     // vite server configs, for details see [vite doc](https://vitejs.dev/config/#server-host)
  8.     port: 3000
  9.   },
  10.   plugins: [
  11.     ...VitePluginNode({
  12.       // Nodejs native Request adapter
  13.       // currently this plugin support 'express', 'nest', 'koa' and 'fastify' out of box,
  14.       // you can also pass a function if you are using other frameworks, see Custom Adapter section
  15.       adapter: 'express',

  16.       // tell the plugin where is your project entry
  17.       appPath: './app.ts',

  18.       // Optional, default: 'viteNodeApp'
  19.       // the name of named export of you app from the appPath file
  20.       exportName: 'viteNodeApp',

  21.       // Optional, default: 'esbuild'
  22.       // The TypeScript compiler you want to use
  23.       // by default this plugin is using vite default ts compiler which is esbuild
  24.       // 'swc' compiler is supported to use as well for frameworks
  25.       // like Nestjs (esbuild dont support 'emitDecoratorMetadata' yet)
  26.       // you need to INSTALL `@swc/core` as dev dependency if you want to use swc
  27.       tsCompiler: 'esbuild',

  28.       // Optional, default: {
  29.       // jsc: {
  30.       //   target: 'es2019',
  31.       //   parser: {
  32.       //     syntax: 'typescript',
  33.       //     decorators: true
  34.       //   },
  35.       //  transform: {
  36.       //     legacyDecorator: true,
  37.       //     decoratorMetadata: true
  38.       //   }
  39.       // }
  40.       // }
  41.       // swc configs, see [swc doc](https://swc.rs/docs/configuration/swcrc)
  42.       swcOptions: {}
  43.     })
  44.   ],
  45.   optimizeDeps: {
  46.     // Vite does not work well with optionnal dependencies,
  47.     // you can mark them as ignored for now
  48.     // eg: for nestjs, exlude these optional dependencies:
  49.     // exclude: [
  50.     //   '@nestjs/microservices',
  51.     //   '@nestjs/websockets',
  52.     //   'cache-manager',
  53.     //   'class-transformer',
  54.     //   'class-validator',
  55.     //   'fastify-swagger',
  56.     // ],
  57.   },
  58. });
  59. ```

Update your server entry to export your app named viteNodeApp or the name you configured.

ExpressJs


  1. ``` ts
  2. const app = express();

  3. // your beautiful code...

  4. if (import.meta.env.PROD)
  5.   app.listen(3000);

  6. export const viteNodeApp = app;
  7. ```

More Examples:


KoaJs
Cloud Functions
Fastify
NestJs
Apollo Server

Add a npm script to run the dev server:

  1. ``` json
  2. "scripts": {
  3.   "dev": "vite"
  4. },
  5. ```

Run the script! npm run dev

Custom Adapter


If your favorite framework not supported yet, you can either create an issue to request it or use the adapter option to tell the plugin how to pass down the request to your app. You can take a look how the supported frameworks implementations from the ./src/server folder. Example:

  1. ``` ts
  2. import { defineConfig } from 'vite';
  3. import { VitePluginNode } from 'vite-plugin-node';

  4. export default defineConfig({
  5.   plugins: [
  6.     ...VitePluginNode({
  7.       adapter({ app, server, req, res, next }) {
  8.         app(res, res);
  9.       },
  10.       appPath: './app.ts'
  11.     })
  12.   ]
  13. });
  14. ```

Build


This plugin leverages Vite SSR mode to build your app. All you need to do is add a build script to your package.json:

  1. ``` json
  2. "scripts": {
  3.   "build": "vite build"
  4. },
  5. ```

For more build config please check vite doc

Note: By default, starting from vite v3, the ssr buildle will be in esm format. if you want to build cjs, add ssr: { format: 'cjs' } to your vite config.


Examples


See the examples folder.

Why?


While frontend development tooling is evolving rapidly in recent years, backend DX is still like in stone age. No hot module replacement; Typescript recompiling slow as funk; Lack of plugin system etc. Thanks to Vite.js created by Evan You (A.K.A creator of vue.js; my biggest idol developer), makes all those dreams for backend development come true!

How?


Vite by design has a middleware mode, which allows us to use it programmatically inside other modules. It's originally made for SSR, so that for each request, vite can load the renderer and render the latest changes you made to your app (https://vitejs.dev/guide/ssr.html ). This plugin leverages this feature to load and execute your server app entry.

You may ask, isn't super slow, since it re-compiles/reloads the entire app? The answer is NO, because vite is smart. It has a builtin module graph as a cache layer, the graph is built up the first time your app loads. After that, when you update a file, vite will only invalidate that one and its parent modules, so that for next request, only those invalidated modules need to be re-compiled which is super fast thanks to esbuild or swc.

To-Do


As this plugin just fresh developed, there are still lots ideas need to be implemented, including:

Test with a large node project, I need y'all helps on this!
Unit tests

Bugs


Please create an issue if you found any bugs, to help me improve this project!
Last Updated: 2023-05-23 11:11:51