[ Web Proxy ]
URL:
Viewing: https://fa.vite.dev/guide/api-javascript [Back]  [Original]

(API) | Vite
Skip to content
Menu
Return to top
Sidebar Navigation

Environment API

    ViteConf Logo [ViteConf Logo]

    Building Together

    ViteConf 2025

    First time in-person!

    (API)

    Vite (typed) IntelliSense (validation) TypeScript (type checking) 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 })

    createServer build (process) Node.js process.env.NODE_ENV mode . process.env.NODE_ENV mode API development . (child process) API .

    (middleware mode) WebSocket HTTP (parent http server) 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://localhost:3000',
    // Proxying WebSocket
    ws
    : true,
    }, }, }, })
    parentServer
    .use(
    vite
    .
    middlewares
    )

    (InlineConfig)

    InlineConfig UserConfig :

    • (configFile): . Vite . false .

    (ResolvedConfig)

    ResolvedConfig UserConfig resolve (undefined ). (utilities) :

    • config.assetsInclude: id asset .
    • 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 (DX) Vite . Tailwind CSS . HTTP1 HTTP . Vite . Vite optimizeDeps.crawlUntilStaticImports: false (cold start) .

    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>

    Vite . isRoot Vite . build false .

    mergeConfig . callback mergeConfig .

    defineConfig callback :

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

    searchForWorkspaceRoot

    :

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

    : server.fs.allow

    workspace root :

    • workspaces package.json
    • :
      • lerna.json
      • pnpm-workspace.yaml

    loadEnv

    :

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

    : .env Files

    .env envDir VITE_ (prefixes) .

    normalizePath

    :

    ts
    function normalizePath(id: string): string

    : Path Normalization

    (path) Vite .

    transformWithEsbuild

    :

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

    JavaScript TypeScript esbuild. Vite .

    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>

    Vite esbuild.

    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 . .module.{ext} CSS module modules .

    url() image-set() resolve .

    Pager

    MIT . (8af0a5dd)


    Web Proxy Viewer  |  New URL  |  Original Page