مطالعهٔ Vite Docs

شروع کار، ساخت نسخهٔ انتشار

باز کردن مرجع کامل دانلود آرشیو مستندات ناشر

گزیده‌ای از مستندات Vite Docs · نسخهٔ 3567471998e3 · MIT

شروع کار

# Getting Started

<audio id="vite-audio"> <source src="/vite.mp3" type="audio/mpeg"> </audio>

Overview

Vite (French word for "quick", pronounced /viːt/<button style="border:none;padding:3px;border-radius:4px;vertical-align:bottom" id="play-vite-audio" aria-label="pronounce" onclick="document.getElementById('vite-audio').play();"><svg style="height:2em;width:2em"><use href="../images/voice.svg?no-inline#voice" /></svg></button>, like "veet") is a build tool that aims to provide a faster and leaner development experience for modern web projects. It consists of two major parts:

  • A dev server that provides rich feature enhancements over native ES modules, for example extremely fast Hot Module Replacement (HMR).
  • A build command that bundles your code with Rolldown, pre-configured to output highly optimized static assets for production.

Vite is opinionated and comes with sensible defaults out of the box. Read about what's possible in the Features Guide. Support for frameworks or integration with other tools is possible through Plugins. The Config Section explains how to adapt Vite to your project if needed.

Vite is also highly extensible via its Plugin API and JavaScript API with full typing support.

You can learn more about the rationale behind the project in the Why Vite section.

<ScrimbaLink href="https://scrimba.com/intro-to-vite-c03p6pbbdq?via=vite" title="Free Vite Course on Scrimba">Learn Vite through interactive tutorials on Scrimba</ScrimbaLink>

Browser Support

During development, Vite assumes that a modern browser is used. This means the browser supports most of the latest JavaScript and CSS features. For that reason, Vite sets [esnext as the transform target](https://oxc.rs/docs/guide/usage/transformer/lowering.html#target). This prevents syntax lowering, letting Vite serve modules as close as possible to the original source code. Vite injects some runtime code to make the development server work. This code uses features included in Baseline Newly Available at the time of each major release (2026-01-01 for this major).

For production builds, Vite by default targets Baseline Widely Available browser versions as of a date fixed for each major release. For this major, that corresponds to browser versions released around mid-2023. The target can be lowered via configuration. Additionally, legacy browsers can be supported via the official @vitejs/plugin-legacy. See the Building for Production section for more details.

Trying Vite Online

You can try Vite online on StackBlitz. It runs the Vite-based build setup directly in the browser, so it is almost identical to the local setup but doesn't require installing anything on your machine. You can navigate to vite.new/{template} to select which framework to use.

The supported template presets are:

JavaScriptTypeScript
vanillavanilla-ts
vuevue-ts
reactreact-ts
preactpreact-ts
litlit-ts
sveltesvelte-ts
solidsolid-ts
qwikqwik-ts

Scaffolding Your First Vite Project

::: code-group

bash [npm]
$ npm create vite@latest
bash [Yarn]
$ yarn create vite
bash [pnpm]
$ pnpm create vite
bash [Bun]
$ bun create vite
bash [Deno]
$ deno init --npm vite

:::

Then follow the prompts!

<ScrimbaLink href="https://scrimba.com/intro-to-vite-c03p6pbbdq/~0yhj?via=vite" title="Scaffolding Your First Vite Project">Watch an interactive lesson on Scrimba</ScrimbaLink>

::: tip Compatibility Note Vite requires Node.js version 20.19+, 22.12+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it. :::

:::: details Using create vite with command line options

You can also directly specify the project name and the template you want to use via additional command line options. For example, to scaffold a Vite + Vue project, run:

::: code-group

bash [npm]
# npm 7+, extra double-dash is needed:
$ npm create vite@latest my-vue-app -- --template vue
bash [Yarn]
$ yarn create vite my-vue-app --template vue
bash [pnpm]
$ pnpm create vite my-vue-app --template vue
bash [Bun]
$ bun create vite my-vue-app --template vue
bash [Deno]
$ deno init --npm vite my-vue-app --template vue

:::

See create-vite for more details on each supported template: vanilla, vanilla-ts, vue, vue-ts, react, react-compiler, react-ts, react-compiler-ts, preact, preact-ts, lit, lit-ts, svelte, svelte-ts, solid, solid-ts, qwik, qwik-ts.

You can use . for the project name to scaffold in the current directory.

To create a project without interactive prompts, you can use the --no-interactive flag.

::::

Community Templates

create-vite is a tool to quickly start a project from a basic template for popular frameworks. Check out Awesome Vite for community maintained templates that include other tools or target different frameworks.

For a template at https://github.com/user/project, you can try it out online using https://github.stackblitz.com/user/project (adding .stackblitz after github to the URL of the project).

You can also use a tool like tiged to scaffold your project with one of the templates. Assuming the project is on GitHub and uses main as the default branch, you can create a local copy using:

bash
npx tiged user/project my-project
cd my-project

npm install
npm run dev

Manual Installation

In your project, you can install the vite CLI using:

::: code-group

bash [npm]
$ npm install -D vite
bash [Yarn]
$ yarn add -D vite
bash [pnpm]
$ pnpm add -D vite
bash [Bun]
$ bun add -D vite
bash [Deno]
$ deno add -D npm:vite

:::

And create an index.html file like this:

html
<p>Hello Vite!</p>

Then run the appropriate CLI command in your terminal:

::: code-group

bash [npm]
$ npx vite
bash [Yarn]
$ yarn vite
bash [pnpm]
$ pnpm vite
bash [Bun]
$ bunx vite
bash [Deno]
$ deno run -A npm:vite

:::

The index.html will be served on http://localhost:5173.

index.html and Project Root

One thing you may have noticed is that in a Vite project, index.html is front-and-central instead of being tucked away inside public. This is intentional: during development Vite is a server, and index.html is the entry point to your application.

Vite treats index.html as source code and part of the module graph. It resolves <script type="module" src="..."> that references your JavaScript source code. Even inline <script type="module"> and CSS referenced via <link href> also enjoy Vite-specific features. In addition, URLs inside index.html are automatically rebased so there's no need for special %PUBLIC_URL% placeholders.

Similar to static http servers, Vite has the concept of a "root directory" which your files are served from. You will see it referenced as <root> throughout the rest of the docs. Absolute URLs in your source code will be resolved using the project root as base, so you can write code as if you are working with a normal static file server (except way more powerful!). Vite is also capable of handling dependencies that resolve to out-of-root file system locations, which makes it usable even in a monorepo-based setup.

Vite also supports multi-page apps with multiple .html entry points.

Specifying Alternative Root

Running vite starts the dev server using the current working directory as root. You can specify an alternative root with vite serve some/sub/dir. Note that Vite will also resolve [its config file (i.e. vite.config.js)](/config/#configuring-vite) inside the project root, so you'll need to move it if the root is changed.

Command Line Interface

In a project where Vite is installed, you can use the vite binary in your npm scripts, or run it directly with npx vite. Here are the default npm scripts in a scaffolded Vite project:

<!-- prettier-ignore -->

json [package.json]
{
  "scripts": {
    "dev": "vite", // start dev server, aliases: `vite dev`, `vite serve`
    "build": "vite build", // build for production
    "preview": "vite preview" // locally preview production build
  }
}

You can specify additional CLI options like --port or --open. For a full list of CLI options, run npx vite --help in your project.

Learn more about the Command Line Interface.

Using Unreleased Commits

If you can't wait for a new release to test the latest features, you can install a specific commit of Vite with https://pkg.pr.new:

::: code-group

bash [npm]
$ npm install -D https://pkg.pr.new/vite@SHA
bash [Yarn]
$ yarn add -D https://pkg.pr.new/vite@SHA
bash [pnpm]
$ pnpm add -D https://pkg.pr.new/vite@SHA
bash [Bun]
$ bun add -D https://pkg.pr.new/vite@SHA

:::

Replace SHA with any of Vite's commit SHAs. Note that only commits within the last month will work, as older commit releases are purged.

Alternatively, you can also clone the vite repo to your local machine and then build and link it yourself (pnpm is required):

bash
git clone https://github.com/vitejs/vite.git
cd vite
pnpm install
cd packages/vite
pnpm run build
pnpm link # use your preferred package manager for this step

Then go to your Vite based project and run pnpm link vite (or the package manager that you used to link vite globally). Now restart the development server to ride on the bleeding edge!

To learn more about how and when Vite does releases, check out the Releases documentation.

::: tip Dependencies using Vite To replace the Vite version used by dependencies transitively, you should use npm overrides or pnpm overrides. :::

Community

If you have questions or need help, reach out to the community at Discord and GitHub Discussions.

ساخت نسخهٔ انتشار

# Building for Production

When it is time to deploy your app for production, simply run the vite build command. By default, it uses <root>/index.html as the build entry point, and produces an application bundle that is suitable to be served over a static hosting service. Check out the Deploying a Static Site for guides about popular services.

<ScrimbaLink href="https://scrimba.com/intro-to-vite-c03p6pbbdq/~037q?via=vite" title="Building for Production">Watch an interactive lesson on Scrimba</ScrimbaLink>

Browser Compatibility

By default, the production bundle targets the minimum browser versions compatible with Baseline Widely Available as of a date fixed for each major release. The default browser support range for this major is:

<!-- Search for the ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET constant for more information -->

  • Chrome >=111
  • Edge >=111
  • Firefox >=114
  • Safari >=16.4

You can specify custom targets via the [build.target config option](/config/build-options.md#build-target), where the lowest target is es2015. If a lower target is set, Vite will still require these minimum browser support ranges as it relies on native ESM dynamic import, and [import.meta](https://caniuse.com/mdn-javascript_operators_import_meta):

<!-- Search for the defaultEsbuildSupported constant for more information -->

  • Chrome >=64
  • Firefox >=67
  • Safari >=11.1
  • Edge >=79

Note that by default, Vite only handles syntax transforms and does not cover polyfills. You can check out https://cdnjs.cloudflare.com/polyfill/ which automatically generates polyfill bundles based on the user's browser UserAgent string.

Legacy browsers can be supported via @vitejs/plugin-legacy, which will automatically generate legacy chunks and corresponding ES language feature polyfills. The legacy chunks are conditionally loaded only in browsers that do not have native ESM support.

Public Base Path

  • Related: Asset Handling

If you are deploying your project under a nested public path, simply specify the [base config option](/config/shared-options.md#base) and all asset paths will be rewritten accordingly. This option can also be specified as a command line flag, e.g. vite build --base=/my/public/path/.

JS-imported asset URLs, CSS url() references, and asset references in your .html files are all automatically adjusted to respect this option during build.

The exception is when you need to dynamically concatenate URLs on the fly. In this case, you can use the globally injected import.meta.env.BASE_URL variable which will be the public base path. Note this variable is statically replaced during build so it must appear exactly as-is (i.e. import.meta.env['BASE_URL'] won't work).

For advanced base path control, check out Advanced Base Options.

Relative base

If you don't know the base path in advance, you may set a relative base path with "base": "./" or "base": "". This will make all generated URLs to be relative to each file.

:::warning Support for older browsers when using relative bases

import.meta support is required for relative bases. If you need to support [browsers that do not support import.meta](https://caniuse.com/mdn-javascript_operators_import_meta), you can use [the legacy plugin](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy).

:::

Customizing the Build

The build can be customized via various build config options. Specifically, you can directly adjust the underlying Rolldown options via build.rolldownOptions:

js [vite.config.js]

  build: {
    rolldownOptions: {
      // https://rolldown.rs/reference/
    },
  },
})

For example, you can specify multiple Rolldown outputs with plugins that are only applied during build.

Chunking Strategy

You can configure how chunks are split using [build.rolldownOptions.output.codeSplitting](https://rolldown.rs/reference/OutputOptions.codeSplitting) (see Rolldown docs). If you use a framework, refer to their documentation for configuring how chunks are split.

Load Error Handling

Vite emits vite:preloadError event when it fails to load dynamic imports. event.payload contains the original import error. If you call event.preventDefault(), the error will not be thrown.

js twoslash
window.addEventListener('vite:preloadError', (event) => {
  window.location.reload() // for example, refresh the page
})

Browsers that support retriable module loading allow an application or framework to retry the original dynamic import after a transient network or HTTP error. Older browsers require a page reload because they cache the failure in the module map.

When a new deployment occurs, the hosting service may delete the assets from previous deployments. As a result, a user who visited your site before the new deployment might encounter an import error. This error happens because the assets running on that user's device are outdated and the code tries to import the corresponding old chunk, which is deleted. This event is useful for addressing this situation. In this case, make sure to set Cache-Control: no-cache on the HTML file, otherwise the old assets will be still referenced.

Rebuild on Files Changes

You can enable Rolldown watcher with vite build --watch. Or, you can directly adjust the underlying [WatcherOptions](https://rolldown.rs/reference/InputOptions.watch) via build.watch:

js [vite.config.js]

  build: {
    watch: {
      // https://rolldown.rs/reference/InputOptions.watch
    },
  },
})

With the --watch flag enabled, changes to files to be bundled will trigger a rebuild. Note that changes to the config and its dependencies require restarting the build command.

Multi-Page App

Suppose you have the following source code structure:

text
├── package.json
├── vite.config.js
├── index.html
├── main.js
└── nested
    ├── index.html
    └── nested.js

During dev, simply navigate or link to /nested/ - it works as expected, just like for a normal static file server.

During build, all you need to do is to specify multiple .html files as entry points:

js twoslash [vite.config.js]



  input: {
    main: resolve(import.meta.dirname, 'index.html'),
    nested: resolve(import.meta.dirname, 'nested/index.html'),
  },
})

If you specify a different root, remember that import.meta.dirname will still be the folder of your vite.config.js file when resolving the input paths. Therefore, you will need to add your root entry to the arguments for resolve.

Note that for HTML files, Vite ignores the name given to the entry in the rolldownOptions.input object and instead respects the resolved id of the file when generating the HTML asset in the dist folder. This ensures a consistent structure with the way the dev server works.

Library Mode

When you are developing a browser-oriented library, you are likely spending most of the time on a test/demo page that imports your actual library. With Vite, you can use your index.html for that purpose to get the smooth development experience.

When it is time to bundle your library for distribution, use the [build.lib config option](/config/build-options.md#build-lib). Make sure to also externalize any dependencies that you do not want to bundle into your library, e.g. vue or react:

::: code-group

js twoslash [vite.config.js (single entry)]



  build: {
    lib: {
      entry: resolve(import.meta.dirname, 'lib/main.js'),
      name: 'MyLib',
      // the proper extensions will be added
      fileName: 'my-lib',
    },
    rolldownOptions: {
      // make sure to externalize deps that shouldn't be bundled
      // into your library
      external: ['vue'],
      output: {
        // Provide global variables to use in the UMD build
        // for externalized deps
        globals: {
          vue: 'Vue',
        },
      },
    },
  },
})
js twoslash [vite.config.js (multiple entries)]



  build: {
    lib: {
      entry: {
        'my-lib': resolve(import.meta.dirname, 'lib/main.js'),
        secondary: resolve(import.meta.dirname, 'lib/secondary.js'),
      },
      name: 'MyLib',
    },
    rolldownOptions: {
      // make sure to externalize deps that shouldn't be bundled
      // into your library
      external: ['vue'],
      output: {
        // Provide global variables to use in the UMD build
        // for externalized deps
        globals: {
          vue: 'Vue',
        },
      },
    },
  },
})

:::

The entry file would contain exports that can be imported by users of your package:

js [lib/main.js]

Running vite build with this config uses a Rollup preset that is oriented towards shipping libraries and produces two bundle formats:

  • es and umd (for single entry)
  • es and cjs (for multiple entries)

The formats can be configured with the [build.lib.formats](/config/build-options.md#build-lib) option.

text
$ vite build
building for production...
dist/my-lib.js      0.08 kB / gzip: 0.07 kB
dist/my-lib.umd.cjs 0.30 kB / gzip: 0.16 kB

Recommended package.json for your lib:

::: code-group

json [package.json (single entry)]
{
  "name": "my-lib",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/my-lib.umd.cjs",
  "module": "./dist/my-lib.js",
  "exports": {
    ".": {
      "import": "./dist/my-lib.js",
      "require": "./dist/my-lib.umd.cjs"
    }
  }
}
json [package.json (multiple entries)]
{
  "name": "my-lib",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/my-lib.cjs",
  "module": "./dist/my-lib.js",
  "exports": {
    ".": {
      "import": "./dist/my-lib.js",
      "require": "./dist/my-lib.cjs"
    },
    "./secondary": {
      "import": "./dist/secondary.js",
      "require": "./dist/secondary.cjs"
    }
  }
}

:::

CSS support

If your library imports any CSS, it will be bundled as a single CSS file besides the built JS files, e.g. dist/my-lib.css. The name defaults to build.lib.fileName, but can also be changed with [build.lib.cssFileName](/config/build-options.md#build-lib).

You can export the CSS file in your package.json to be imported by users:

json {12}
{
  "name": "my-lib",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/my-lib.umd.cjs",
  "module": "./dist/my-lib.js",
  "exports": {
    ".": {
      "import": "./dist/my-lib.js",
      "require": "./dist/my-lib.umd.cjs"
    },
    "./style.css": "./dist/my-lib.css"
  }
}

::: tip File Extensions If the package.json does not contain "type": "module", Vite will generate different file extensions for Node.js compatibility. .js will become .mjs and .cjs will become .js. :::

::: tip Environment Variables In library mode, all [import.meta.env.*](./env-and-mode.md) usage are statically replaced when building for production. However, process.env.* usage are not, so that consumers of your library can dynamically change it. If this is undesirable, you can use define: { 'process.env.NODE_ENV': '"production"' } for example to statically replace them, or use [esm-env](https://github.com/benmccann/esm-env) for better compatibility with bundlers and runtimes. :::

::: warning Advanced Usage Library mode includes a simple and opinionated configuration for browser-oriented and JS framework libraries. If you are building non-browser libraries, or require advanced build flows, you can use tsdown or Rolldown directly. :::

Advanced Base Options

::: warning This feature is experimental. Give Feedback. :::

For advanced use cases, the deployed assets and public files may be in different paths, for example to use different cache strategies. A user may choose to deploy in three different paths:

  • The generated entry HTML files (which may be processed during SSR)
  • The generated hashed assets (JS, CSS, and other file types like images)
  • The copied public files

A single static base isn't enough in these scenarios. Vite provides experimental support for advanced base options during build, using experimental.renderBuiltUrl.

ts twoslash

// prettier-ignore
const config: UserConfig = {
// ---cut-before---
experimental: {
  renderBuiltUrl(filename, { hostType }) {
    if (hostType === 'js') {
      return { runtime: `window.__toCdnUrl(${JSON.stringify(filename)})` }
    } else {
      return { relative: true }
    }
  },
},
// ---cut-after---
}

If the hashed assets and public files aren't deployed together, options for each group can be defined independently using asset type included in the second context param given to the function.

ts twoslash


// prettier-ignore
const config: UserConfig = {
// ---cut-before---
experimental: {
  renderBuiltUrl(filename, { hostId, hostType, type }) {
    if (type === 'public') {
      return 'https://www.domain.com/' + filename
    } else if (path.extname(hostId) === '.js') {
      return {
        runtime: `window.__assetsPath(${JSON.stringify(filename)})`
      }
    } else {
      return 'https://cdn.domain.com/assets/' + filename
    }
  },
},
// ---cut-after---
}

Note that the filename passed is a decoded URL, and if the function returns a URL string, it should also be decoded. Vite will handle the encoding automatically when rendering the URLs. If an object with runtime is returned, encoding should be handled yourself where needed as the runtime code will be rendered as is.