Open the Network panel in a Vite project and you'll see the browser requesting /src/main.ts. Browsers don't understand TypeScript, yet the page still runs. When you run a build, the original module may no longer exist as such: several files are bundled into one JS file, and a single dynamic import may pull in several chunks.
That's where the problem lies: the source code we write, the modules Vite processes, and the files the browser downloads are already three different things. Looking only at the configuration makes it easy to treat them as the same thing.
This article explains Vite in the order an actual project needs it: first, create the project and work with configuration, TypeScript, CSS, and assets; then, look at development requests, hot updates, builds, and deployment. With those foundations in place, we can unpack plugin Hooks and then see how React, SSR, server functions, and Workers runtimes fit in. Whenever something isn't clear, we'll return to a concrete module and examine where it came from, what it was changed into, and who executes it.
This article comes with 11 progressive labs. Readers should know how to use JavaScript's import/export, Promises, and the basic command line; React is used only in the relevant chapters. Every lab can run locally and requires no cloud account. The source pins Vite 8.3.4, React 19.3.1, and @vitejs/plugin-react 6.1.2; the validation environment uses Node 24.22.0 and pnpm 10.24.0. See the verification notes for the reproducible scope and records.
The article's section numbers differ from the course numbers: sections proceed in explanatory order, while course numbers only identify the corresponding labs. Readers who only need everyday development and delivery can start with the first two parts; the plugin and framework material builds on that foundation.
- Foundations: What Vite does · Creating a project · Configuration and TypeScript · CSS and assets
- Development and delivery: Module serving · HMR and React · mode and env · Building and deploying
- Extension mechanisms: The core Hook lifecycle
- Frameworks and practice: Multi-environment SSR · Server functions · Ecosystem integrations · Troubleshooting · Verification
Part One: Project and Modules
1. What Vite does
First, separate development from deployment. During dev, Vite receives browser requests, transforms source code, and maintains module relationships; during build, it collects dependencies from entry points and organizes files that can be deployed. These are two ways of delivering the program, but in either case the final program is executed by the browser or a server runtime.
So, for a React button on a page to work, at least two things must happen: the source code must be transformed into executable JS, and the React runtime must turn the component into DOM. Vite connects the former; it does not do the latter on React's behalf. Later, when deciding whether a capability needs a plugin, first determine which of these steps it belongs to.
Check the version before reading the source. Vite 8 in this article uses the Rust-based Rolldown bundler and integrates Oxc; the default Refresh transform in React plugin v6 also uses Oxc. The common explanation that “development uses esbuild while production uses Rollup” has its own version context; using it to analyze the call chain here will point you to the wrong tools. The Vite 8 release notes list the changes.
The Rust bundler can call JavaScript plugins: Vite's configuration and plugin functions run in Node's JavaScript environment, while native bindings pass the required calls and results to Rust. The two languages collaborate through an interface, and plugins do not have to be written in Rust. To observe calls in both directions, run the companion JS/Rust mini-lab. It demonstrates synchronous bindings without simulating Rolldown's complete scheduling system.
2. Creating a project from scratch: first, three commands
You can create a new project with the official scaffold:
pnpm create vite my-app --template vanilla-ts
cd my-app
pnpm install
pnpm dev
The scaffold changes with each release. To reproduce the results in this article, use the companion repository and lockfile:
git clone --branch v1.0.0 https://github.com/liyown/vite-study.git
cd vite-study
pnpm install --frozen-lockfile
pnpm dev 01
The minimum Node requirements for Vite 8 are 20.19+ or 22.12+; a template may require an even newer version. This repository uses .node-version to specify the validation version. For project creation, see the official getting started guide.
| Command | Input | Output or behavior |
|---|---|---|
vite / vite dev | Source code and configuration | Starts the development server and serves modules as needed |
vite build | Build entry point and its dependencies | Generates production artifacts, usually in dist |
vite preview | Existing dist | Checks the build locally without recompiling it |
Once the project is set up, open index.html before rushing into the configuration. A web application enters through this HTML file under root by default, and its module script pulls in the code that follows:
Vite processes this HTML and then follows the module script to find its dependencies. That is why it must live at the project root; don't copy another tool's directory conventions and put the entry point in public. Root does not have to be the Git repository root either: in a multi-project repository, starting from the wrong directory can cause Vite to miss the configuration and env files as well.
The entry point and module graph lab (course 01) provides the initial observation point: refresh the page, record Network activity, then click “Load Editor” and inspect the new requests. Next, run a build, open the manifest, and compare where the module ends up in production. The difference between source relationships and delivered files will appear in these two results.
3. Configuration, module resolution, and TypeScript: what each one does
A common configuration file looks like this:
This configuration is loaded on the Node side, so the node:url import does not thereby enter the browser. defineConfig helps check the configuration's types; command tells us whether we are running serve or build, while mode is a separate choice that we'll discuss later. The alias uses an absolute path so that resolution results don't shift with the startup directory. For differences between configuration loaders, see the official configuration reference.
Module resolution has to answer the question “where does this import point?” Relative paths, package names, and aliases each follow their own resolution rules. A package's exports, conditions, and target environment can also affect the final choice. A path with incorrect capitalization may go unnoticed locally and only surface on a Linux build machine.
If your editor accepts a path but the builder says it cannot find the module, check TypeScript and Vite's resolution configurations separately. The configuration and assets lab (course 02) explicitly configures paths and alias. Disabling Vite's alias causes module resolution to fail; to observe a type-checking failure, temporarily override paths in the child tsconfig with {}, then run pnpm exec tsc --noEmit -p examples/02-project-basics/tsconfig.json. Merely deleting the child configuration entry makes it inherit the root mapping and does not isolate the condition. Restore the file and confirm that the check passes afterward. Vite 8 also offers the optional resolve.tsconfigPaths; this lab uses explicit configuration so that the responsibilities on both sides remain visible.
Now make one small change: pass a number to a function that accepts only strings. The build may still succeed, while tsc --noEmit reports the type error. What Vite does here is transpilation; a project must integrate type checking separately into development or CI. Network input has another layer to consider as well: giving JSON a TypeScript type does not prevent the server from actually returning invalid data.
4. How CSS, images, and text enter the module graph
When you see imports like the following, first work out what each variable holds; don't treat them all as meaning “bring a file into the project”:
logoUrl is the most instructive of these. During development, it points to an asset URL. After the build, it may point to a file with a hash in its name or to an inline data URL. Once an image is imported, Vite can track it and rewrite the reference.
public follows a separate route. Files there are served and copied unchanged, which makes it suitable for assets whose filenames must be preserved. When base is /, the URL for public/handbook.txt is /handbook.txt, without public. When deploying under a subpath, use import.meta.env.BASE_URL to construct public asset URLs; the course uses ${import.meta.env.BASE_URL}handbook.txt. Choosing this route means accepting that its files do not participate in the same hash management. For details such as inline thresholds, see the assets guide.
CSS Modules provide local class names, but CSS's cascade and selector rules still apply. Preprocessors such as Sass and Less require the corresponding implementation to be installed; PostCSS and other CSS tools each have their own configuration. It is usually easier to troubleshoot the processing pipeline with plain CSS first and then introduce tools according to the project's needs.
Bulk loading can also enter the dependency graph:
What you get here is not a collection of text that has already been read, but a table mapping “path → loader function.” Clicking an article calls the corresponding function, which is what triggers the load; adding eager: true makes it an immediate import instead. The pattern must be a static literal because Vite needs to know the dependency set in advance and cannot traverse your source directory only after deployment.
The usual way to create a Worker is:
Vite can analyze this form and process the Worker's source and production URL. At runtime, communication still happens through messages, and a Worker cannot access the page's DOM. See the built-in features guide for the supported scope of glob, CSS, and Worker support. The assets lab places these capabilities on one page so that you can inspect them one by one.
Part Two: Development and Delivery
5. How the development server lets the browser execute TypeScript
Return to /src/main.ts from the beginning. Open it in Network and look at the Response, not just the filename. The type annotations are gone, and the import paths may have changed. The browser executes the JavaScript in this response; .ts is only the URL suffix for this development request.
As you follow this process, you'll see that business modules are served on demand rather than waiting for the entire application to finish a production bundle. Transformed modules can hit the cache, and preloading may request some dependencies early. This diagram describes processing relationships; it is not a script that starts over from scratch on every request.
Now consider a package import: import React from 'react'. The browser does not search inside node_modules using Node's package-resolution rules. Vite has to resolve the package first and deliver a URL that the browser can request. Dependency pre-bundling also handles CommonJS/UMD compatibility and cases where a dependency produces too many requests for its internal modules. The dependency pre-bundling guide explains when Vite rebuilds the cache and when it reuses it.
If a linked local package only works after a second startup, or a CommonJS package fails only during development, inspect the resolution results and optimization logs before reaching for optimizeDeps.include/exclude. I wouldn't start by assembling a long list of configuration options. You can use --force to rule out the effects of an old cache; if you have to add it every time, the problem has not been diagnosed yet.
Development optimizations cannot replace production validation. Production also performs tree shaking, code splitting, minification, and asset output. The fact that the application runs in development validates only one path.
6. How HMR turns file changes into page updates
During development, another URL often appears in Network: /@vite/client. This is the development client injected by Vite. It receives updates, coordinates module replacement, and handles styles and error messages. When you save a file, the server and client exchange update messages; the browser then loads any new modules it needs.
Downloading the new code isn't enough for the page to know how it should change. The server's module graph first finds an acceptance boundary, and the browser also needs to know what to execute after receiving the new exports. Here is that part written out directly:
The key is nextModule.getMessage(). The initial assignment uses the old module, while the updated assignment happens in this callback. If you remove the callback, Vite does not know which function produced the existing DOM and cannot reproduce it for you. It continues along the module relationships to find a boundary and reloads the page if necessary. See the HMR API for the conventions governing acceptance boundaries and invalidation propagation.
CSS is an easy example to observe. During development, a regular CSS import becomes JavaScript that calls updateStyle, and the module accepts its own updates. Running it again updates the corresponding style element. The source is .css, so it is not a contradiction for the update message to say js-update. At the end of the lifecycle, prune can clean up the corresponding style.
When resources need cleanup, use dispose for listeners, timers, and similar resources; when a small amount of data must survive an update, use hot.data. HMR does not automatically manage every side effect in your application.
What the React plugin adds
Run the controlled comparison between bare React and Fast Refresh: execute pnpm dev 03 and pnpm dev 04 in separate terminals, open :5173 and :5174, and click both counters up to 3. Change only the title of each Counter: the bare configuration resets to zero, while the side with the React plugin remains at 3. Both sides have the same business source, and both could already transform the TSX.
pnpm compare:react checks the actual transformation results. The two flags in the output are:
03-react-bare jsxWasTransformed: true hasRefreshInstrumentation: false
04-react-refresh jsxWasTransformed: true hasRefreshInstrumentation: true
The fact that JSX has been transformed only means that its syntax was processed. Component registration and the code that accepts updates are what connect the change to Refresh. Changing Hook order or invalidating an export boundary can still reset state, so the result of editing a title does not generalize to arbitrary modifications.
This step is easy to misread. The parent module may still hold Counter_v1, and the JSX does indeed pass that function to React. Where the new implementation is selected, React's development rendering flow first finds the family through the component function and then reads the current implementation. The family relates the versions, while Fiber stores instance state. If you mistake this for ESM automatically replacing every old import, the HMR assumptions you make later for ordinary JavaScript will be wrong.
For the React plugin's boundary handling, compare the pinned source. In a React project, the Refresh Runtime and the renderer's hot-reload handling show how the two sides work together. The main links are for reading; the reproducible lab still uses the versions pinned in the repository.
7. Keep mode, environment variables, and runtime targets separate
| Name | What it determines | Example |
|---|---|---|
| mode | Selects a set of development/build configurations and env files | development、staging |
NODE_ENV | Affects development/production runtime semantics and related constants | development、production |
| Vite Environment | The current module's resolution, transformation, and build context | client、ssr |
| runtime | The host that actually executes the program | browser、Node、workerd |
Without a preset NODE_ENV, vite build --mode staging has a MODE of staging, while PROD is still true. --mode development also does not turn a production build into a development server merely because of its name. The mode and env lab (course 05) shows the commands and actual values side by side. The mode guide explains the difference between mode and NODE_ENV.
Variables with the same name override one another in the following order, from lowest to highest precedence: .env → .env.local → .env.[mode] → .env.[mode].local → environment variables that already exist when the process starts. A value defined in only one file is still available. Restart the development server after changing env files.
In the browser, import.meta.env.VITE_FEATURE is usually a string. Boolean('false') is still true, so parse it explicitly according to your application's conventions. VITE_ means that the variable is allowed into the client bundle by default, not that it is encrypted or hidden. When the configuration stage needs to read env variables, use loadEnv; don't stuff all of process.env into the client-side define.
Why doesn't the frontend change after you modify an env variable following deployment? Open the generated JS and look for the value: it was written in at build time, while changing the server's environment now affects a different process. If the value genuinely must change after deployment, have the server return a public runtime configuration, or inject it into the HTML and define which fields the browser may read.
8. How a production build merges modules and splits chunks
First distinguish two terms: a module is a unit in the dependency graph, while a chunk is a code file delivered to the user. The build organizes modules into chunks, and the two do not have to correspond one to one. The build and deployment lab (course 06) demonstrates this with two HTML entry points and one dynamic module:
Here, shared is used by both the home page and the admin page. Copying it twice would waste code, while extracting it would add dependency requests; the bundler has to arrange things according to the dependency graph and output strategy. A dynamic import provides an on-demand loading boundary, but when shared dependencies are involved, one call may require several files. If you expect every source file to produce one JS file, the output will soon be confusing.
What happens to imports when filenames change? Open an entry artifact and you can see that import('./lazy.ts') has become a path such as import('./assets/lazy-abc123.js'). References between declarations and duplicate variable names must also be handled. The builder therefore has to understand module relationships. A path string written casually into JSON has no such import relationship, so there is no reason to expect it to be renamed automatically.
The entry lab provides another observation point: first see unused exports disappear, then add a top-level console.log to a module. Even if nobody calls it, it has changed the module's evaluation behavior and cannot simply be deleted as “unused.” Tree shaking depends on static analysis and side-effect information; setting sideEffects incorrectly to false may also remove initialization that is genuinely needed.
Manual chunking changes loading and sharing relationships and can even affect when side effects run. More files cannot be equated with faster delivery. The Rolldown code-splitting guide explains the available controls. Observe the real dependencies, the entry download size, and loading during interactions before deciding whether to adjust chunking manually.
The build and deployment lab also covers multipage builds, dynamic modules, and library builds. The common configuration options are:
| Configuration | Purpose and limitations |
|---|---|
base | The public base path for assets; it must match the path where the server actually mounts the application |
build.target | Controls target syntax compatibility; it does not automatically polyfill every missing browser API |
build.manifest | Outputs mappings for entry points, assets, and dependencies for backend templates or inspection tools |
build.sourcemap | Outputs debugging maps, which may expose source code and therefore require an explicit distribution policy |
build.rolldownOptions | Configures underlying build options such as inputs and outputs |
build.lib | Builds a library with code exports as its entry points; declaration files, exports, and dependency conventions also need consideration |
Website builds care about HTML and browser assets by default, while library builds care about which exports consumers can import. Publishing a TypeScript library also requires type declaration generation. See the production build guide for the related configuration.
Deploying artifacts consistently
For a static website, you can give dist to a static server or CDN. vite preview is for local inspection. The official deployment guide lists integration options for different platforms.
When base is /study/, the server must map that path to the artifacts as well. Client-side routing in an SPA needs an HTML fallback, while a multipage site needs the corresponding HTML files. Missing JS, CSS, and API requests should not be mistaken for HTML through a fallback, since that commonly leads to MIME type errors.
Another problem appears only after deployment: a user leaves an old page open, then clicks a dynamic feature later, only for the chunk requested by the old JS to have been removed by a new deployment. A hash identifies file content, but it does not guarantee that the old file still exists. HTML and assets must be delivered from matching versions, and old assets need a retention policy. HTML is usually revalidated against the cache, while hashed assets can be cached for longer. SSR also requires deploying the server entry point and its external dependencies; uploading only the client directory is not enough.
Part Three: Extending Vite
9. How the core plugin Hooks fit together
Now open plugins, and the problem becomes more concrete. A plugin may supplement configuration, turn special files into JS, or install an interface on the development server. A factory returns a Hook object for these tasks and may also return an array of plugins. plugins: [a(), b()] registers handlers, and Vite calls them at different stages during the run.
When reading plugin source, I first look for the kind of input the plugin takes over. Configuration changes, module handling, request handling, and artifact generation live in different places. Copying every Hook into an execution-order table can instead make the code harder to read.
Configuration stage: turning user configuration into a usable context
While configuration is still being merged, the config hook can add an alias or a define. By configResolved, the final root and other results are available to read and can be saved for later use. Changing configuration at this point does not make Vite redo resolutions that have already completed. This is also not the moment when “a module is being transformed for the client environment,” so you cannot attach this.environment to every configuration Hook.
Module stage: how a name becomes executable source code
Walk through import { message } from 'virtual:lesson':
Here is the smallest possible plugin:
No file is created here. resolveId claims the public name and assigns it an internal ID; load provides source code for that ID. The following steps can then treat it as a module. If the generated source contains an import, dependency analysis will continue to follow it. The RPC registry later in this article enters the server module graph in exactly this way.
| Hook | Typical input | What receives a valid result |
|---|---|---|
resolveId | Import string, importer, and resolution options | The resolved module ID, passed to the loading step |
load | Module ID | The module source, passed to the transformation step |
transform | Current source and module ID | The new source and map, passed to subsequent transformation and analysis |
The three Hooks also cooperate differently. Once a plugin has provided a valid load result, another loader usually does not need to provide the source again; transform, on the other hand, may continue processing the previous plugin's result. They are not the same kind of reduce. Before writing a plugin, check the return type: null, strings, objects, and arrays play different roles in different Hooks. See the Plugin API for the exact conventions.
The text macro in the plugin lab (course 07) handles only an agreed suffix, replaces one controlled placeholder, and returns a source map. This limited scope makes the problem clear with text processing alone. If you need to identify that a call named createServerFn really comes from a particular package, a regular expression is not enough: a local variable can have the same name, and an import can use an alias. The framework compilation lab later introduces ASTs and binding analysis. Complexity should be determined by the semantics you need to handle.
Development stage: server setup and change propagation
configureServer has access to the development server, so you can install middleware there. Returning a post-installation function lets you place middleware after Vite's internal handling. But a build does not copy that closure into dist. The development interface in the plugin lab disappears during preview specifically to make this boundary visible. The production API is provided separately in the later Node API lab.
transformIndexHtml can participate in both development and builds, so you cannot classify it merely by asking whether it is a “Vite-owned Hook.” Hot updates are similar: the new hotUpdate and the compatible handleHotUpdate each have their own environment context, so check the version in use.
The plugin lab's text loader returns an importable string, this.addWatchFile declares files to watch, and hotUpdate sends a notification; the page's accept callback then updates the corresponding DOM. These parts work together to complete a hot update. No single Hook is enough to guarantee that business state is preserved.
Build stage: how modules enter the final output
The development container also reuses some build Hooks, such as buildStart during initialization; ordinary development requests do not enter the complete chunk output stage.
Two measured results show why you should not memorize one fixed order. In a trace using the pinned versions, outputOptions can run before buildStart. When a user's generateBundle is called, Vite may not yet have generated the HTML. If a plugin wants to modify the HTML at this point, assuming that “generateBundle has already happened” leads to the wrong conclusion. Either choose an appropriate HTML Hook or check the output order of the relevant plugins.
Below is an excerpt from the write-build log produced by pnpm docs:hooks:trace, with the module transformation calls in the middle omitted:
options
outputOptions
buildStart
...
generateBundle { isWrite: true, hasHtml: false }
transformIndexHtml
writeBundle
hasHtml: false describes only the output set at the moment this probe was called; it does not mean that Vite did not generate HTML. The HTML is added during a later stage, so both the Hook's stage and the plugin order need to be considered.
transform examines one module, renderChunk examines an organized chunk, and generateBundle examines the file set for that output. At the final point, modules, imports, and dynamicImports let you answer where the source was placed and how the bundles depend on one another. Use emitFile to add a JSON report, then wait for the builder to write it to disk.
The function-manifest.json, compiled text, and build-report.json files in the framework compilation lab are there to be read. The actual RPC lookup table is generated in load. Treating the report as the execution mechanism adds a runtime chain that does not actually exist.
The shutdown logic also deserves separate validation. A build may fail halfway through initialization, while an output failure follows a different error path; the repository's controlled error tracing has also observed repeated closeBundle calls. Releasing resources should be idempotent, and statistics should be reset for each build round. Otherwise, after watching for a while, the report may mix in data from earlier rounds.
Limits on ordering and environment state
enforce: 'pre'/'post' changes a plugin's position among plugin groups, and some Hooks support their own order. Configuration and notifications, parallel and serial processing, and first versus consecutive processing each have their own conventions. Properties such as apply and applyToEnvironment also restrict the scenarios in which a plugin is active.
Multi-environment plugins should read this.environment in Hooks that support an environment context. When sharing a plugin instance across environments, use a Map keyed by environment to store records, and have buildStart clear only the records for the current round and environment. Configuration Hook and module Hook contexts are not interchangeable.
The complete reference contains all Hooks, controls, and context members, while the arrow lifecycle connects them. pnpm docs:hooks compares the documentation with the type checking provided by the installed versions; pnpm docs:hooks:trace runs six paths—including successful builds, errors, development, and preview—to generate real scheduling records. The complete checklist is useful for finding omissions, but it cannot replace observing a specific invocation.
Part Four: Frameworks and Practice
10. How multiple Environments support SSR
So far, we have mainly been dealing with browser programs. Adding SSR introduces a new problem: the same App must generate HTML on the server in one copy and pick up interactions in the browser in another. The source can be shared, but the entry points and execution targets are different.
If you simply add an ssr boolean to the same graph, you quickly run into more differences: which conditional export should a package use? Should a plugin generate browser code or server code? Where should the output go? Environment separates these processing contexts, and a single Vite development server can serve multiple graphs. It is not a process count; runtime is the host in which the code actually executes. The Environment API formally describes these relationships, although some interfaces are still evolving.
The multi-environment SSR lab (course 08) declares client and ssr and enables the application builder. Here are just the environment and entry configuration, with imports, the React plugin, and the HTTP host omitted; the runnable configuration is in the course source:
The configuration declares the processing targets, while the application builder orchestrates those targets. Merely declaring environments does not imply that every arbitrary build command will automatically produce all of them; the SSR lab includes a comparison with the application builder removed. The framework interface explains how application builds and development environments are orchestrated.
An SSR request also needs an HTTP host:
Notice the “call render” step in the diagram. Vite can hand a server module to a runner for execution, but an HTTP host still has to catch the request, retrieve the export, and call it. The SSR lab implements this orchestration in server.mjs, so you can trace directly to the point where the export is invoked. The SSR guide presents this as a low-level integration.
The browser must then hydrate with the same initial data. If the server calculates a random value first and the browser calculates another one, the two outputs no longer match. Initial data also means public delivery: anything written into the HTML can be read by the browser. Serialization must handle characters such as closing tags as well; simply concatenating raw JSON into the HTML is not enough.
The Node API lab (course 09) separately demonstrates CSR + Node API: the development server proxies requests, while production uses Node to serve the API and static assets. It does not configure a second Vite graph for the backend. Full-stack APIs, SSR, and multiple environments solve different problems; they can be combined or adopted independently.
11. How one server-function source can generate programs for both sides
The minimal RPC lab (course 10) keeps only one function and a short plugin. The business module exports greet(name) and uses a Node API internally; the page still imports it like an ordinary function.
The plugin handles the module differently for each environment during transformation:
同一个 greet.server.js
├─ client → 整个模块替换成 fetch('/rpc/greet') 代理
└─ ssr → 保留真正的 Node 实现
The server entry imports a virtual registry generated by the plugin, whose contents are equivalent to:
The function is found at the registry[id]() step. There is no remote transmission of a function and no search on disk for a declaration named greet. The compiler has already encoded that “this ID loads this module.” After bundling, the ID can still be greet, while the import path becomes ./assets/greet.server-某个hash.js. The relationship between the two identifiers is stored in the code and maintained when the bundler rewrites module references.
The minimal RPC treats the entire file as one server function, which is why it can remain small. Now relax one condition: the same file must also export constants used by the page. Replacing the entire file no longer works. Supporting import aliases, local variables with the same name, and shared helpers also requires knowledge of bindings. The framework compilation lab's AST compiler addresses these concrete problems, allowing you to add the conditions one at a time.
Where TanStack Start fits
The framework compilation lab (course 11) refers to the pinned commit 7a0672503857283614799a0b480f4a82110e5ab6 of TanStack/router. In that snapshot's server-function compiler, you can see roles such as the client caller, SSR caller, and provider. The local source comparison lists the adopted and omitted mechanisms one by one.
The provider is the most confusing part here. The server itself also needs code that calls the interface: one piece is the caller that wants to call getGreeting, and the other is the implementation that retains the real handler. The plugin uses ?server-fn-provider to give the latter a different module ID, and transform generates the implementation-side code when it sees the query. Both remain in the ssr graph; adding another identity does not add a third environment or require a third server.
Do not group every API with a similar name under RPC. createIsomorphicFn selects a local implementation for each side; createServerFn lets a call cross to the server; createServerOnlyFn restricts the execution target but does not automatically publish an endpoint. TanStack's server-function guide describes how the full framework uses these APIs, while the teaching API covers only part of them.
A remotely callable function is ultimately an entry point for external input. A production application also needs permissions, input validation, error handling, request context, and a transport protocol. Removing the client handler at compile time does not replace server-side authorization. The client bundle is not the only public channel either: secrets in SSR initial data, or the original implementation left in a public source map, can still leak.
The source map was the component that actually failed in this implementation. When inspecting the client JS, the handler and Node cryptographic dependency had both been removed. Inspecting the map revealed that sourcesContent had brought the original handler back. The code-execution path was isolated, but the source-distribution path leaked.
The exact trigger was a transform that removed the handler but returned { mappings: '' }, with source maps enabled for the client build. During subsequent processing in Vite 8.3.4, the final sourcesContent included the original text containing createHmac. You can compare the broken and current versions in a temporary directory with the following command. The script cleans up its temporary output and does not modify the course source:
pnpm --filter @vite-study/11-mini-start compare:maps
The current version points the mapping at the safe transformed source and checks both the JS and the map. The cost is losing precise mapping back to the original business source. This result is limited to the mapping and build chain described above; it does not show that an empty map will leak in every tool. A production framework needs a more complete mapping strategy that balances isolation against mapping precision.
12. How ecosystem frameworks usually integrate with Vite
Breaking a “framework plugin” down by responsibility makes it easier to locate problems than looking only at the plugins array:
| Integration layer | Common work | What to inspect |
|---|---|---|
| Syntax and component development | JSX, single-file components, development registration, HMR boundaries | Transformed modules and editing behavior |
| Application framework | Routing, dual-side entry points, data loading, SSR, server-function compilation | Module graphs on both sides, call protocol, artifacts |
| Runtime and deployment adaptation | Development execution host, bindings, request interfaces, build and deployment assets | Actual runtime capabilities, request entry point, deployment configuration |
The React plugin mainly participates in the first layer. TanStack Start combines application conventions with a runtime, while the Cloudflare plugin connects the corresponding environment to Workers' development and deployment systems. One framework may span several layers. This table distinguishes responsibilities rather than defining mutually exclusive package categories.
Workers explain why the third layer is necessary. If code always runs locally in Node during development but is handed to a different runtime after deployment, the APIs, module behavior, and bindings you validated in development may not be the ones used in production. In its article introducing the Vite plugin, Cloudflare presents integrating workerd into the development environment as an important change. The problem it solves is where the code executes; the build output directory is only part of that.
The framework remains responsible for organizing the application, while the runtime provider makes the code in the corresponding environment execute in the correct host. Vite's runtime interface and the Cloudflare plugin documentation explain this seam in detail.
Vite, frameworks, and runtime adapters connect through conventions for environments, entry points, and requests. A plugin factory may return multiple plugins that each handle different Hooks; array order is only one part of ordering. A real project should start from the framework's official integration template and then inspect the final configuration, rather than assembling the plugin arrays from several independent tutorials. For the specific configuration of TanStack Start + Cloudflare, consult the official integration guide. The companion repository validates the Node-based teaching implementation and does not claim to complete this cloud deployment.
When reading an unfamiliar Vite framework, locate these pieces in order: how configuration is loaded, which environments exist, the entry point for each environment, how special imports are resolved and transformed, the host that actually executes the code, and the handler that ultimately receives requests. Once you have found these locations, much of a framework's code can be assigned to a specific responsibility.
13. Troubleshoot performance and failures by stage
For a performance problem, first identify which step is slow. Is the application inaccessible for a long time after the startup command runs? Is the first load slow? Are updates slow after saving? Is the production first view slow? Behind the same statement that “Vite is slow” may be work in four different places. Bundling speed and the download size experienced by users should also be measured separately.
| Symptom | What to inspect first | Common directions |
|---|---|---|
| Slow startup or first page load | Dependency optimization logs, Network, plugin transformation time | New dependency scanning, overly broad transformation scope, expensive plugins, request waterfalls |
| Slow updates or full-page reloads after editing | HMR messages, module import relationships, framework boundaries | Widely imported modules, invalidation propagation, heavy transformations |
| Failure only in production | Full build logs, artifacts, preview requests | Capitalization, static-analysis limits, asset paths, external dependencies |
| A JS request returns HTML | Response and Content-Type, server fallback | Incorrect base/mount path, expired old assets, overly broad fallback rules |
An SSR window error | The entry indicated by the stack, top-level code in shared modules | Browser-only logic entering the server target |
| CI type checking fails but build succeeds | Separate type checking and each tool's resolution configuration | Transpilation and type checking have different responsibilities; alias configurations do not align |
For example, suppose a plugin traverses the entire src directory on every transform. One scan may look fast, but as the number of modules grows, the same directory tree is read over and over. You should first adjust when scans happen and how their caches are invalidated, rather than changing vendor chunking. Use logs or a profiler to locate the cost, then perform the same operation before and after the change. If there is no difference, you have no basis for calling the change an optimization. The Vite performance guide provides a starting point for measurement.
Choose tests according to their level: use unit tests for pure functions; check plugin transformations through their inputs and outputs; use integration tests for the development server and SSR/RPC; and use real browser interactions for HMR state preservation and hydration behavior. Tools such as Vitest can fit into the Vite ecosystem, but this article uses Node's test runner to validate builds and services so that it does not introduce another test framework and then have to explain its configuration.
14. Verify the article with the companion labs
Master everyday usage along the main path first, then move on to the extension mechanisms:
Each section's README provides the run location, source-reading order, modifications to try, expected behavior, and a self-test. Restore your changes after the lab, then run:
pnpm check
It runs type checking, builds every course, validates behavior, checks documentation links and course order, and verifies Hook coverage. Browser interactions and cloud deployment are not automatically covered by this command; see the verification record for its scope.
When you finish, you can test your understanding with a practical task: draw an “HTML/server entry point → module graph → transformation → artifact → request handling” diagram for your own project, then mark one dynamic module, one framework HMR boundary, and one server-only dependency. Every arrow in the diagram should have corresponding evidence in Network activity, the source, or a build report.
Author: Liu Yaowen. This article originated from this set of local learning labs; AI assisted with implementing and organizing the code and prose. The verification commands, versions, and uncovered scope remain in the companion course material. Please submit corrections through repository Issues.