跳轉到內容

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

僅為了向後相容而保留。