new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vite · Guide · all subjects

general

42 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Vite composition: dev server and build command

Vite consists of two major parts: a dev server that provides rich feature enhancements over native ES modules with extremely fast Hot Module Replacement (HMR), and a build command that bundles code with Rolldown, pre-configured to output highly optimized static assets for production.

index.html is entry point and treated as source code

In a Vite project, index.html is the entry point to the application and is treated as source code, part of the module graph. Vite resolves script type="module" tags that reference JavaScript source code, and also processes inline script modules and CSS linked via link href. URLs inside index.html are automatically rebased so there is no need for special placeholders like %PUBLIC_URL%.

Vite project root and file serving

Vite has a concept of a root directory from which files are served. Absolute URLs in source code are resolved using the project root as base. Vite can handle dependencies that resolve to out-of-root file system locations, making it usable in monorepo-based setups.

Vite is opinionated with sensible defaults

Vite is opinionated and comes with sensible defaults out of the box. It is highly extensible via its Plugin API and JavaScript API with full typing support. Customization is possible through configuration if needed.

Consistent CommonJS default import handling

In Vite 8, the default import from a CommonJS module is handled consistently. The default import is the module.exports value if: the importer is .mjs or .mts, the closest package.json has type: 'module', or the importee's module.exports.__esModule is not set to true. Otherwise, the default import is module.exports.default.

legacy.inconsistentCjsInterop option for backward compatibility

Vite 8 provides a deprecated legacy.inconsistentCjsInterop: true option to temporarily restore the previous inconsistent CommonJS import behavior if needed for compatibility with existing code.

Removed module resolution using format sniffing

Vite 8 no longer uses format sniffing to choose between browser and module fields in package.json. It now always respects the order of the resolve.mainFields option. To work around this if needed, use resolve.alias to map the field to the desired file or apply a patch with your package manager.

require calls for externalized modules preserved

In Vite 8, require calls for externalized modules are now preserved as require calls and not converted to import statements. To convert them to imports, use Rolldown's built-in esmExternalRequirePlugin, which is re-exported from vite.

Deprecated options in Vite 8

The following options are deprecated in Vite 8 and will be removed in the future: build.rollupOptions (renamed to build.rolldownOptions), worker.rollupOptions (renamed to worker.rolldownOptions), build.commonjsOptions (now no-op), build.dynamicImportVarsOptions.warnOnError (now no-op), resolve.alias[].customResolver (use a custom plugin with resolveId hook and enforce: 'pre' instead).

esmExternalRequirePlugin usage example

To preserve require calls for externalized modules as imports in Vite 8, use the esmExternalRequirePlugin from vite: import { defineConfig, esmExternalRequirePlugin } from 'vite'; export default defineConfig({ plugins: [esmExternalRequirePlugin({ external: ['react', 'vue', /^node:/] })] })

rolldown-vite intermediate migration path

Users migrating from Vite 7 to Vite 8 can use rolldown-vite as an intermediate step. To complete migration from rolldown-vite to Vite 8, update package.json from 'vite': 'npm:rolldown-vite@7.2.2' to 'vite': '^8.0.0'.

Import path resolution is expensive with many extensions

Vite supports guessing import paths using resolve.extensions. When resolving an import without an extension, Vite checks each extension in order. For example, importing './Component' when Component.jsx exists requires checking './Component', './Component.mjs', './Component.js', './Component.mts', './Component.ts', and finally './Component.jsx' before finding it. This means 6 filesystem checks are required. Being explicit with import paths (e.g., 'import ./Component.jsx') avoids this overhead. You can also narrow down the resolve.extensions list to reduce filesystem checks, but must ensure it still works for files in node_modules.

Browser extensions and cache can impact Vite dev server performance

Browser extensions can interfere with requests and slow down startup and reload times, especially for large apps. Create a dev-only profile without extensions or use incognito mode when using Vite's dev server. Incognito mode is faster than a regular profile without extensions. The Vite dev server implements hard caching of pre-bundled dependencies and fast 304 responses for source code. Disabling the cache while Browser Dev Tools are open significantly impacts startup and full-page reload times, so ensure the 'Disable Cache' setting is not enabled while working with Vite.

Profiling Vite performance with CPU profile

You can run vite --profile, visit the site, and press p + enter in your terminal to record a .cpuprofile. Tools like speedscope can then be used to inspect the profile and identify bottlenecks. Profiles can also be shared with the Vite team to help identify performance issues.

resolve.extensions default value

The resolve.extensions option defaults to ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'].

Barrel files performance impact

Barrel files are files that re-export the APIs of other files in the same directory. When importing an individual API from a barrel file, all files in that barrel need to be fetched and transformed because they may contain the requested API and may also have side-effects that run on initialization. This results in loading more files than required on the initial page load, causing slower page loads. It is better to avoid barrel files and import individual APIs directly instead.

server.warmup option for frequently used files

The Vite dev server only transforms files as requested by the browser, allowing fast startup. Request waterfalls can occur if some files take longer to transform than others. The server.warmup option allows pre-transforming frequently used files that you anticipate will be requested. For example, if BigComponent.vue takes time to transform and blocks big-utils.js, you can warm up big-utils.js so it is ready and cached when requested. Only warm up frequently used files to avoid overloading the Vite dev server on startup.

server.warmup configuration example

export default defineConfig({ server: { warmup: { clientFiles: [ './src/components/BigComponent.vue', './src/utils/big-utils.js', ], }, }, }) This example shows how to configure frequently used files to be pre-transformed using the server.warmup option with clientFiles array.

Automatic warmup with --open or server.open

Using --open or server.open provides a performance boost because Vite will automatically warm up the entry point of your app or the provided URL to open.

Reduce work by using native CSS and avoiding SVG transformation

To keep Vite fast with growing codebases, reduce the amount of work for source files. Use CSS instead of Sass/Less/Stylus when possible, as nesting can be handled by PostCSS or Lightning CSS. Don't transform SVGs into UI framework components (React, Vue, etc.); import them as strings or URLs instead.

TypeScript moduleResolution configuration for performance

If using TypeScript, enable "moduleResolution": "bundler" and "allowImportingTsExtensions": true in tsconfig.json's compilerOptions to use .ts and .tsx extensions directly in your code, which improves performance.

Node.js modules cannot be used in browser

Vite enforces that Node.js modules cannot be used in the browser, pushing developers toward writing modern, browser-compatible code.

Vite source code requires ESM only

Vite source code can only be written in ESM. Non-ESM dependencies must be pre-bundled as ESM in order to work with Vite.

Full bundle mode exploration for very large codebases

Since exceptionally large codebases can experience slow page loads due to the high number of unbundled network requests, the Vite team is exploring a full bundle mode where the dev server bundles code similarly to production, reducing network overhead. This is possible because Rolldown provides both the speed and the HMR and plugin capabilities needed to bundle during dev.

Why dev server startup is nearly instant in Vite

Dev server startup in Vite is nearly instant regardless of application size because dependencies are pre-bundled separately from source code, and source code is served on-demand over native ESM rather than being bundled upfront like traditional bundlers.

Vite's Environment API for custom build targets

Instead of treating only 'client' and 'SSR' as build targets, the Environment API lets frameworks define custom environments such as edge runtimes and service workers, each with their own module resolution and execution rules.

Vite's two-part development approach: dependencies and source code

Vite splits development work into two parts: Dependencies (libraries that rarely change) are pre-bundled once using fast native tooling and are ready instantly. Source code (the application code that changes frequently) is served on-demand over native ESM, with the browser loading only what it needs for the current page and Vite transforming each file as it is requested.

Ecosystem health as part of Vite's release process

The Vite team runs vite-ecosystem-ci, which tests major ecosystem projects against every Vite change. Ecosystem health is not an afterthought but is part of the release process.

Profile Vite dev server and build for performance bottlenecks

To identify performance bottlenecks, start the built-in Node.js inspector with Vite using vite --profile --open for dev server or vite build --profile for build. For the dev server, wait for the app to load in the browser, then press 'p' in the terminal to stop the Node.js inspector and 'q' to stop the dev server. The inspector generates vite-profile-0.cpuprofile in the root folder. Upload this file to https://www.speedscope.app/ using the BROWSE button to inspect the results.

Use vite-plugin-inspect to identify performance bottlenecks

The vite-plugin-inspect plugin allows you to inspect the intermediate state of Vite plugins and helps identify which plugins or middlewares are performance bottlenecks. It can be used in both dev and build modes.

Cross drive links on Windows prevent Vite from working

Vite may not work if there are cross drive links in the project on Windows, such as a virtual drive linked to a folder by subst command or a symlink/junction to a different drive by mklink command (e.g., Yarn global cache).

ESM-only package import error in vite.config.js

When importing an ESM-only package using require() in vite.config.js, Node.js <=22 throws an error because ESM files cannot be loaded by require() by default. To fix this, convert the config to ESM by either adding "type": "module" to the nearest package.json or renaming vite.config.js/vite.config.ts to vite.config.mjs/vite.config.mts.

File descriptor and inotify limits cause stalled requests on Linux

On Linux, file descriptor limits and inotify limits may cause requests to stall forever because Vite does not bundle most files, causing browsers to request many files that require many file descriptors. Increase the file descriptor limit using ulimit -Sn (e.g., ulimit -Sn 10000) and increase inotify limits using sysctl: fs.inotify.max_queued_events=16384, fs.inotify.max_user_instances=8192, and fs.inotify.max_user_watches=524288. These settings are temporary; for permanent changes, add DefaultLimitNOFILE=65536 to /etc/systemd/system.conf and /etc/systemd/user.conf, or add * - nofile 65536 to /etc/security/limits.conf on Ubuntu.

ENOSPC error when project has many files on Linux

The ENOSPC error occurs on Linux when a project has too many files (e.g., many images or assets) and exceeds the system's file watcher limit, which defaults to around 8,192-10,000. To solve this, increase the limit by setting fs.inotify.max_user_watches=524288 (check current with cat /proc/sys/fs/inotify/max_user_watches, make permanent by adding to /etc/sysctl.conf and running sudo sysctl -p), exclude directories from file watching using server.watch.ignored, or use polling instead of file system events with server.watch.usePolling (note: polling uses more CPU).

Self-signed SSL certificate causes network requests to stop loading

When using a self-signed SSL certificate, Chrome ignores all caching directives and reloads content. Vite relies on these caching directives, so network requests will stop loading. To resolve this, use a trusted SSL certificate. On macOS, you can install a trusted certificate via CLI with: security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db your-cert.cer, or import it into Keychain Access and set trust to "Always Trust".

431 Request Header Fields Too Large error

When the server or WebSocket server receives a large HTTP header, the request is dropped and a 431 status code warning is shown. This is because Node.js limits request header size to mitigate CVE-2018-12121. To avoid this, reduce request header size (e.g., delete long cookies) or use --max-http-header-size flag to change the max header size.

VS Code Dev Container requires server.host set to 127.0.0.1

When using a Dev Container or port forwarding feature in VS Code, set the server.host configuration option to 127.0.0.1 to make it work. This is because VS Code's port forwarding feature does not support IPv6.

Default import from CJS module returns module.exports object

When importing a default export from a CommonJS module, the import returns the module.exports object instead of the module.exports.default value. This can cause errors like "Element type is invalid: expected a string or class/function but got: object" or "foo is not a function". Refer to Rolldown's documentation on ambiguous default imports from CJS modules for more details.

Node.js modules externalized for browser compatibility

When using Node.js modules (like 'fs') in browser code, Vite outputs a warning that the module has been externalized for browser compatibility and its functions cannot be accessed in client code. This is because Vite does not automatically polyfill Node.js modules. It is recommended to avoid Node.js modules for browser code to reduce bundle size. If the module is imported from a third-party library meant for the browser, report the issue to that library.

Vite does not support code in non-strict mode (sloppy mode)

Vite cannot handle and does not support code that only runs in non-strict mode because Vite uses ESM and it is always in strict mode inside ESM. Errors may occur like "With statements cannot be used with the esm output format due to strict mode" or "TypeError: Cannot create property 'foo' on boolean 'false'". If these codes are in dependencies, use patch-package, yarn patch, or pnpm patch to fix them.

Browser extensions may prevent Vite client from communicating with dev server

Some browser extensions (like ad-blockers) may prevent the Vite client from sending requests to the Vite dev server, resulting in a white screen without logged errors or a "TypeError: Failed to fetch dynamically imported module" error. Try disabling extensions to fix this issue.

Node.js version requirement for Vite

Vite requires Node.js version 20.19+, 22.12+. Some templates may require a higher Node.js version, so you should upgrade if your package manager warns about it.

Give your agent this brain