コンテンツをスキップ

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 設定オプションに依存します。競合する動作を防ぐために、2 つの API の process.env.NODE_ENV または modedevelopment に設定します。それ以外の場合は、子プロセスを生成して API を別々に実行できます。

注意

ミドルウェアモードWebSocket のプロキシ設定を組み合わせる場合は、親の HTTP サーバーを middlewareMode で指定してプロキシを正しくバインドする必要があります。

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: .env ファイルを無効にするには false に設定します。

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>
}

INFO

waitForRequestsIdleは、Vite devサーバーのオンデマンドの性質に従って実装できない機能のDXを改善するためのエスケープハッチとして使用することを目的としています。Tailwindのようなツールによって起動時に使用して、アプリのCSSクラスをアプリコードが認識されるまで生成を遅らせ、スタイル変更のちらつきを回避できます。この関数がロードまたは変換フックで使用され、デフォルトのHTTP1サーバーが使用されると、サーバーがすべての静的インポートを処理するまで、6つのhttpチャネルの1つがブロックされます。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の値はdevとpreviewでserveであり、buildでbuildです。

mergeConfig

型シグネチャ

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

2つのVite設定をディープマージします。isRootは、マージされるVite設定のレベルを表します。たとえば、2つの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.jsonworkspacesフィールドが含まれている
  • 以下のファイルのいずれかが含まれている
    • lerna.json
    • pnpm-workspace.yaml

loadEnv

型シグネチャ

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

関連: .envファイル

envDir内の.envファイルを読み込みます。デフォルトでは、prefixesが変更されない限り、VITE_でプレフィックスされた環境変数のみが読み込まれます。

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)