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.
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:
- Chrome >=111
- Edge >=111
- Firefox >=114
- Safari >=16.4
You can specify custom targets via the build.target config option, 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:
- 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 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.
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, you can use the legacy plugin.
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:
export default defineConfig({
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 (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.
windowvar window: Window & typeof globalThisThe window property of a Window object points to the window object itself.
.addEventListenerfunction addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void (+1 overload)The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
('vite:preloadError', (eventevent: Event) => {
windowvar window: Window & typeof globalThisThe window property of a Window object points to the window object itself.
.locationlocation: LocationThe read-only location property of the Window interface returns a Location object with information about the current location of the document.
.reloadLocation.reload(): voidThe reload() method of the Location interface reloads the current URL, like the Refresh button.
() // 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 via build.watch:
export default defineConfig({
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:
├── package.json
├── vite.config.js
├── index.html
├── main.js
└── nested
├── index.html
└── nested.jsDuring 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:
import { resolvefunction (method) resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
} from 'node:path'
import { defineConfigfunction defineConfig(config: UserConfig): UserConfig (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
} from 'vite'
export default defineConfigfunction defineConfig(config: UserConfig): UserConfig (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
({
inputinput?: InputOption | undefinedEntry points of the application.
Paths are resolved relative to the project root.
: {
mainmain: string: resolvefunction resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, 'index.html'),
nestednested: string: resolvefunction resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, '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. Make sure to also externalize any dependencies that you do not want to bundle into your library, e.g. vue or react:
import { resolvefunction (method) resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
} from 'node:path'
import { defineConfigfunction defineConfig(config: UserConfig): UserConfig (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
} from 'vite'
export default defineConfigfunction defineConfig(config: UserConfig): UserConfig (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
({
buildbuild?: BuildEnvironmentOptions | undefinedBuild specific options
: {
libBuildEnvironmentOptions.lib?: false | LibraryOptions | undefinedBuild in library mode. The value should be the global name of the lib in
UMD mode. This will produce esm + cjs + umd bundle formats with default
configurations that are suitable for distributing libraries.
: {
entryLibraryOptions.entry?: InputOption | undefinedPath of library entry.
Defaults to the top-level input option when omitted.
: resolvefunction resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, 'lib/main.js'),
nameLibraryOptions.name?: string | undefinedThe name of the exposed global variable. Required when the formats option includes
umd or iife
: 'MyLib',
// the proper extensions will be added
fileNameLibraryOptions.fileName?: string | ((format: ModuleFormat, entryName: string) => string) | undefinedThe name of the package file output. The default file name is the name option
of the project package.json. It can also be defined as a function taking the
format as an argument.
: 'my-lib',
},
rolldownOptionsBuildEnvironmentOptions.rolldownOptions?: RolldownOptions | undefinedWill be merged with internal rolldown options.
https://rolldown.rs/reference/Interface.RolldownOptions
: {
// make sure to externalize deps that shouldn't be bundled
// into your library
externalInputOptions.external?: ExternalOption | undefinedSpecifies which modules should be treated as external and not bundled. External modules will be left as import statements in the output.
: ['vue'],
outputRolldownOptions.output?: OutputOptions | OutputOptions[] | undefined: {
// Provide global variables to use in the UMD build
// for externalized deps
globalsOutputOptions.globals?: Record<string, string> | GlobalsFunction | undefinedSpecifies id: variableName pairs necessary for
InputOptions.external
external
imports in umd / iife
OutputOptions.format
formats
.
: {
vuevue: string: 'Vue',
},
},
},
},
})import { resolvefunction (method) resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
} from 'node:path'
import { defineConfigfunction defineConfig(config: UserConfig): UserConfig (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
} from 'vite'
export default defineConfigfunction defineConfig(config: UserConfig): UserConfig (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
({
buildbuild?: BuildEnvironmentOptions | undefinedBuild specific options
: {
libBuildEnvironmentOptions.lib?: false | LibraryOptions | undefinedBuild in library mode. The value should be the global name of the lib in
UMD mode. This will produce esm + cjs + umd bundle formats with default
configurations that are suitable for distributing libraries.
: {
entryLibraryOptions.entry?: InputOption | undefinedPath of library entry.
Defaults to the top-level input option when omitted.
: {
'my-lib': resolvefunction resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, 'lib/main.js'),
secondarysecondary: string: resolvefunction resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, 'lib/secondary.js'),
},
nameLibraryOptions.name?: string | undefinedThe name of the exposed global variable. Required when the formats option includes
umd or iife
: 'MyLib',
},
rolldownOptionsBuildEnvironmentOptions.rolldownOptions?: RolldownOptions | undefinedWill be merged with internal rolldown options.
https://rolldown.rs/reference/Interface.RolldownOptions
: {
// make sure to externalize deps that shouldn't be bundled
// into your library
externalInputOptions.external?: ExternalOption | undefinedSpecifies which modules should be treated as external and not bundled. External modules will be left as import statements in the output.
: ['vue'],
outputRolldownOptions.output?: OutputOptions | OutputOptions[] | undefined: {
// Provide global variables to use in the UMD build
// for externalized deps
globalsOutputOptions.globals?: Record<string, string> | GlobalsFunction | undefinedSpecifies id: variableName pairs necessary for
InputOptions.external
external
imports in umd / iife
OutputOptions.format
formats
.
: {
vuevue: string: 'Vue',
},
},
},
},
})The entry file would contain exports that can be imported by users of your package:
import Bar from './Bar.vue'
import Foo from './Foo.vue'
export { Foo, Bar }Running vite build with this config uses a Rollup preset that is oriented towards shipping libraries and produces two bundle formats:
esandumd(for single entry)esandcjs(for multiple entries)
The formats can be configured with the build.lib.formats option.
$ 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 kBRecommended package.json for your lib:
{
"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"
}
}
}{
"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.
You can export the CSS file in your package.json to be imported by users:
{
"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"
}
}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.
Environment Variables
In library mode, all import.meta.env.* 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 for better compatibility with bundlers and runtimes.
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.
experimentalUserConfig.experimental?: ExperimentalOptions | undefinedExperimental features
Features under this field could change in the future and might NOT follow semver.
Please be careful and always pin Vite's version when using them.
: {
renderBuiltUrlExperimentalOptions.renderBuiltUrl?: RenderBuiltAssetUrl | undefinedAllow finegrain control over assets and public files paths
(filenamefilename: string, { hostTypehostType: "js" | "css" | "html" }) {
if (hostTypehostType: "js" | "css" | "html" === 'js') {
return { runtimeruntime?: string | undefined: `window.__toCdnUrl(${JSONvar JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
.stringifyJSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
(filenamefilename: string)})` }
} else {
return { relativerelative?: boolean | undefined: true }
}
},
},
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.
experimentalUserConfig.experimental?: ExperimentalOptions | undefinedExperimental features
Features under this field could change in the future and might NOT follow semver.
Please be careful and always pin Vite's version when using them.
: {
renderBuiltUrlExperimentalOptions.renderBuiltUrl?: RenderBuiltAssetUrl | undefinedAllow finegrain control over assets and public files paths
(filenamefilename: string, { hostIdhostId: string, hostTypehostType: "js" | "css" | "html", typetype: "asset" | "public" }) {
if (typetype: "asset" | "public" === 'public') {
return 'https://www.domain.com/' + filenamefilename: string
} else if (pathconst path: path.PlatformPath.extnamepath.PlatformPath.extname(path: string): stringReturn the extension of the path, from the last '.' to end of string in the last portion of the path.
If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string.
(hostIdhostId: string) === '.js') {
return {
runtimeruntime?: string | undefined: `window.__assetsPath(${JSONvar JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
.stringifyJSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
(filenamefilename: string)})`
}
} else {
return 'https://cdn.domain.com/assets/' + filenamefilename: string
}
},
},
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.
