跳转到内容

JavaScript API

Vite 的 JavaScript API 是完全类型化的。建议使用 TypeScript 或在 VS Code 中启用 JS 类型检查,以利用智能提示和验证功能。

createServer

类型签名

ts
async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>

用法示例

ts
import { 
createServer
} from 'vite'
const
server
= await
createServer
({
// any valid user config options, plus `mode` and `configFile`
configFile
: false,
root
: import.meta.
dirname
,
server
: {
port
: 1337,
}, }) await
server
.
listen
()
server
.
printUrls
()
server
.
bindCLIShortcuts
({
print
: true })

注意

在同一个 Node.js 进程中使用 createServerbuild 时,这两个函数都依赖 process.env.NODE_ENV 来正常工作,而这又取决于 mode 配置选项。为防止行为冲突,请将这两个 API 的 process.env.NODE_ENVmode 设置为 development。或者,你可以生成一个子进程来分别运行这些 API。

注意

当使用 中间件模式 并结合 WebSocket 代理配置 时,应在 middlewareMode 中提供父级 http 服务器,以正确绑定代理。

示例
ts
import 
http
from 'http'
import {
createServer
} from 'vite'
const
parentServer
=
http
.
createServer
() // or express, koa, etc.
const
vite
= await
createServer
({
server
: {
// Enable middleware mode
middlewareMode
: {
// Provide the parent http server for proxy WebSocket
server
:
parentServer
,
},
proxy
: {
'/ws': {
target
: 'ws://:3000',
// Proxying WebSocket
ws
: true,
}, }, }, })
parentServer
.use(
vite
.
middlewares
)

InlineConfig

InlineConfig 接口扩展了 UserConfig,包含额外属性

  • configFile:指定要使用的配置文件。如果未设置,Vite 将尝试从项目根目录自动解析。设置为 false 可禁用自动解析。

ResolvedConfig

ResolvedConfig 接口拥有与 UserConfig 相同的所有属性,不同之处在于大多数属性都已解析且不为 undefined。它还包含一些工具,例如:

  • config.assetsInclude:检查 id 是否被视为资源文件的函数。
  • config.logger:Vite 的内部日志记录对象。

ViteDevServer

ts
interface ViteDevServer {
  /**
   * The resolved Vite config object.
   */
  config: ResolvedConfig
  /**
   * A connect app instance
   * - Can be used to attach custom middlewares to the dev server.
   * - Can also be used as the handler function of a custom http server
   *   or as a middleware in any connect-style Node.js frameworks.
   *
   * https://github.com/senchalabs/connect#use-middleware
   */
  middlewares: Connect.Server
  /**
   * Native Node http server instance.
   * Will be null in middleware mode.
   */
  httpServer: http.Server | null
  /**
   * Chokidar watcher instance. If `config.server.watch` is set to `null`,
   * it will not watch any files and calling `add` or `unwatch` will have no effect.
   * https://github.com/paulmillr/chokidar/tree/3.6.0#api
   */
  watcher: FSWatcher
  /**
   * WebSocket server with `send(payload)` method.
   */
  ws: WebSocketServer
  /**
   * Rollup plugin container that can run plugin hooks on a given file.
   */
  pluginContainer: PluginContainer
  /**
   * Module graph that tracks the import relationships, url to file mapping
   * and hmr state.
   */
  moduleGraph: ModuleGraph
  /**
   * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
   * in middleware mode or if the server is not listening on any port.
   */
  resolvedUrls: ResolvedServerUrls | null
  /**
   * Programmatically resolve, load and transform a URL and get the result
   * without going through the http request pipeline.
   */
  transformRequest(
    url: string,
    options?: TransformOptions,
  ): Promise<TransformResult | null>
  /**
   * Apply Vite built-in HTML transforms and any plugin HTML transforms.
   */
  transformIndexHtml(
    url: string,
    html: string,
    originalUrl?: string,
  ): Promise<string>
  /**
   * Load a given URL as an instantiated module for SSR.
   */
  ssrLoadModule(
    url: string,
    options?: { fixStacktrace?: boolean },
  ): Promise<Record<string, any>>
  /**
   * Fix ssr error stacktrace.
   */
  ssrFixStacktrace(e: Error): void
  /**
   * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
   * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
   */
  reloadModule(module: ModuleNode): Promise<void>
  /**
   * Start the server.
   */
  listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
  /**
   * Restart the server.
   *
   * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
   */
  restart(forceOptimize?: boolean): Promise<void>
  /**
   * Stop the server.
   */
  close(): Promise<void>
  /**
   * Bind CLI shortcuts
   */
  bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void
  /**
   * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
   * are processed. If called from a load or transform plugin hook, the id needs to be
   * passed as a parameter to avoid deadlocks. Calling this function after the first
   * static imports section of the module graph has been processed will resolve immediately.
   * @experimental
   */
  waitForRequestsIdle: (ignoredId?: string) => Promise<void>
}

信息

waitForRequestsIdle 旨在作为一种应急方案,以改善那些无法遵循 Vite 开发服务器按需加载特性的功能的开发体验。它可以在启动时被 Tailwind 等工具使用,以延迟生成应用 CSS 类,直到应用代码被识别,从而避免样式闪烁。在 load 或 transform 钩子中使用此函数,且使用默认的 HTTP1 服务器时,六个 http 通道中的一个将被阻塞,直到服务器处理完所有静态导入。Vite 的依赖预构建目前使用此函数来避免在缺少依赖时进行全页重载,通过推迟预构建依赖的加载,直到所有导入的依赖都已从静态导入源中收集完毕。Vite 未来可能会在主版本升级中切换到不同的策略,默认设置 optimizeDeps.crawlUntilStaticImports: false 以避免在大型应用冷启动时产生的性能损耗。

build

类型签名

ts
async function build(
  inlineConfig?: InlineConfig,
): Promise<RollupOutput | RollupOutput[]>

用法示例

vite.config.js
ts
import 
path
from 'node:path'
import {
build
} from 'vite'
await
build
({
root
:
path
.
resolve
(import.meta.
dirname
, './project'),
base
: '/foo/',
build
: {
rollupOptions
: {
// ... }, }, })

preview

类型签名

ts
async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>

用法示例

ts
import { 
preview
} from 'vite'
const
previewServer
= await
preview
({
// any valid user config options, plus `mode` and `configFile`
preview
: {
port
: 8080,
open
: true,
}, })
previewServer
.
printUrls
()
previewServer
.
bindCLIShortcuts
({
print
: true })

PreviewServer

ts
interface PreviewServer {
  /**
   * The resolved vite config object
   */
  config: ResolvedConfig
  /**
   * A connect app instance.
   * - Can be used to attach custom middlewares to the preview server.
   * - Can also be used as the handler function of a custom http server
   *   or as a middleware in any connect-style Node.js frameworks
   *
   * https://github.com/senchalabs/connect#use-middleware
   */
  middlewares: Connect.Server
  /**
   * native Node http server instance
   */
  httpServer: http.Server
  /**
   * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
   * if the server is not listening on any port.
   */
  resolvedUrls: ResolvedServerUrls | null
  /**
   * Print server urls
   */
  printUrls(): void
  /**
   * Bind CLI shortcuts
   */
  bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void
}

resolveConfig

类型签名

ts
async function resolveConfig(
  inlineConfig: InlineConfig,
  command: 'build' | 'serve',
  defaultMode = 'development',
  defaultNodeEnv = 'development',
  isPreview = false,
): Promise<ResolvedConfig>

command 的值在开发和预览模式下为 serve,在构建模式下为 build

mergeConfig

类型签名

ts
function mergeConfig(
  defaults: Record<string, any>,
  overrides: Record<string, any>,
  isRoot = true,
): Record<string, any>

深度合并两个 Vite 配置。isRoot 表示正在合并的 Vite 配置层级。例如,如果你正在合并两个 build 选项,请设置为 false

注意

mergeConfig 仅接受对象形式的配置。如果你有回调形式的配置,应在传递给 mergeConfig 之前先调用它。

你可以使用 defineConfig 助手将回调形式的配置与另一个配置合并。

ts
export default 
defineConfig
((
configEnv
) =>
mergeConfig
(
configAsCallback
(
configEnv
),
configAsObject
),
)

searchForWorkspaceRoot

类型签名

ts
function searchForWorkspaceRoot(
  current: string,
  root = searchForPackageRoot(current),
): string

相关: server.fs.allow

如果潜在的工作区根目录满足以下条件,则搜索它,否则回退到 root

  • package.json 中包含 workspaces 字段
  • 包含以下任一文件
    • lerna.json
    • pnpm-workspace.yaml

loadEnv

类型签名

ts
function loadEnv(
  mode: string,
  envDir: string,
  prefixes: string | string[] = 'VITE_',
): Record<string, string>

相关: .env 文件

加载 envDir 中的 .env 文件。默认情况下,只加载以 VITE_ 开头的环境变量,除非修改了 prefixes

normalizePath

类型签名

ts
function normalizePath(id: string): string

相关: 路径规范化

规范化路径以在 Vite 插件之间进行互操作。

transformWithOxc

类型签名

ts
async function transformWithOxc(
  code: string,
  filename: string,
  options?: OxcTransformOptions,
  inMap?: object,
): Promise<Omit<OxcTransformResult, 'errors'> & { warnings: string[] }>

使用 Oxc Transformer 转换 JavaScript 或 TypeScript。对于希望匹配 Vite 内部 Oxc Transformer 转换行为的插件非常有用。

transformWithEsbuild

类型签名

ts
async function transformWithEsbuild(
  code: string,
  filename: string,
  options?: EsbuildTransformOptions,
  inMap?: object,
): Promise<ESBuildTransformResult>

已废弃: 请改用 transformWithOxc

使用 esbuild 转换 JavaScript 或 TypeScript。对于希望匹配 Vite 内部 esbuild 转换行为的插件非常有用。

loadConfigFromFile

类型签名

ts
async function loadConfigFromFile(
  configEnv: ConfigEnv,
  configFile?: string,
  configRoot: string = process.cwd(),
  logLevel?: LogLevel,
  customLogger?: Logger,
): Promise<{
  path: string
  config: UserConfig
  dependencies: string[]
} | null>

使用 esbuild 手动加载 Vite 配置文件。

preprocessCSS

类型签名

ts
async function preprocessCSS(
  code: string,
  filename: string,
  config: ResolvedConfig,
): Promise<PreprocessCSSResult>

interface PreprocessCSSResult {
  code: string
  map?: SourceMapInput
  modules?: Record<string, string>
  deps?: Set<string>
}

.css.scss.sass.less.styl.stylus 文件预处理为普通 CSS,以便在浏览器中使用或被其他工具解析。类似于 内置的 CSS 预处理支持,如果使用,必须安装相应的预处理器。

所使用的预处理器由 filename 扩展名推断。如果 filename.module.{ext} 结尾,它会被推断为 CSS 模块,返回的结果将包含一个 modules 对象,用于将原始类名映射到转换后的类名。

注意,预处理不会解析 url()image-set() 中的 URL。

version

类型: string

当前 Vite 的版本号(例如 "8.0.0")。

rolldownVersion

类型: string

Vite 所使用的 Rolldown 版本(例如 "1.0.0")。这是从 rolldown 导出的 VERSION

esbuildVersion

类型: string

仅为了向后兼容而保留。

rollupVersion

类型: string

仅为了向后兼容而保留。