跳至內容

JavaScript API

Vite 的 JavaScript API 是完全型別化的,建議使用 TypeScript 或在 VS Code 中啟用 JS 型別檢查,以利用智能提示和驗證。

createServer

類型簽名

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

使用範例

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

注意

在同一個 Node.js 進程中使用 createServerbuild 時,兩個函式都依賴 process.env.NODE_ENV 來正常運作,這也取決於 mode 設定選項。為了防止衝突行為,將 process.env.NODE_ENV 或兩個 API 的 mode 設定為 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://127.0.0.1:3000',
// Proxying WebSocket
ws
: true,
}, }, }, })
parentServer
.use(
vite
.
middlewares
)

InlineConfig

InlineConfig 介面使用額外屬性擴展了 UserConfig

  • configFile:指定要使用的設定檔。如果未設定,Vite 將嘗試從專案根目錄自動解析一個。設定為 false 以停用自動解析。
  • envFile:設定為 false 以停用 .env 檔案。

ResolvedConfig

ResolvedConfig 介面具有與 UserConfig 相同的所有屬性,只是大多數屬性都已解析且非未定義。它還包含諸如以下的實用工具:

  • 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
  /**
   * Web socket 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 hook 中使用,並且使用預設的 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 {
fileURLToPath
} from 'node:url'
import {
build
} from 'vite'
const
__dirname
=
fileURLToPath
(new
URL
('.', import.meta.
url
))
await
build
({
root
:
path
.
resolve
(
__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 外掛程式之間進行互操作。

transformWithEsbuild

類型簽名

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

使用 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。

在 MIT 許可下發布。(ccee3d7c)