The Inner Workings of Vite Build

Rate this content
Bookmark

Vite unbundled ESM dev server and fast HMR are game-changing for DX. But Vite also shines when building your production applications.

This talk will dive into how the main pieces fit together to bundle and minify your code:

  • Vite build as an opinionated Rollup setup.
  • How esbuild is used as a fast TS and JSX transpile and a minifier.
  • The production plugins pipeline.

Modern frameworks (Nuxt, SvelteKit, Astro, among others) have chosen Vite, augmenting the DX and optimizations for their target use case.

We'll discover Vite as a polished and extendable toolkit to craft optimized modern apps.

This talk has been presented at DevOps.js Conf 2022, check out the latest edition of this Tech Conference.

FAQ

Vite is a modern build tool that focuses on speed and performance. It offers a fast development server with instant module transformation and hot module replacement, making it ideal for modern web development. Vite also excels at building applications for production, using Rollup to bundle and optimize assets.

Matias Capeleto, also known as Patak, is a core team member of Vite and Vitez, as well as a Vue team member. He works full-time on Vite and its ecosystem as part of the Stacklists team.

During development, Vite transforms modules on demand over native ESM as the browser requests them. This allows for lightning-fast hot module replacement (HMR) that remains fast regardless of the application's size.

Vite offers out-of-the-box support for TypeScript, JSX, PostCSS, CSS modules, and more. It also provides a powerful plugin API based on Rollup, allowing for extensions such as Vue single-file components and other frameworks.

You can try Vite with a Vue project by visiting 'vite.new/vue' in your browser. This opens a StackBlitz playground that forks the Vue starter project from the Vite repository, allowing you to experiment with Vite and Vue instantly.

For production, Vite uses Rollup to bundle and optimize all assets of your application. The build process starts with the index.html entry point, extracting scripts and styles, and then processes and minifies each chunk. The output files are hashed for strong caching, and a vendor chunk is generated and preloaded to avoid a loading waterfall.

During the build process, Vite extracts and processes both linked and inline CSS, minifies it using ESBuild, and handles code splitting. Other assets like images, videos, and WebAssembly (WASM) modules are also processed by the build pipeline.

Plugins in Vite extend its functionality and are based on an extended version of the Rollup plugin API. They allow for features such as aliasing import paths, handling CSS modules and preprocessors, importing JSON files, and managing dynamic imports. Most Rollup plugins are compatible with Vite.

You can contribute to the Vite community by participating in issue triage on the Vite repository, joining the Vite Discord community, helping others with their questions, or contributing to the documentation. The Vite community is welcoming and actively collaborates to improve the project.

Migrating from Create React App to Vite is relatively straightforward. There is a project called 'webpack-to-vite' that can help automate the conversion process. The migration mainly involves removing Webpack, adding Vite, and changing a few configuration options.

Matias Capeletto
Matias Capeletto
31 min
25 Mar, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Welcome to vidBuild, a tool that optimizes your application for production by offering fast hodgemodule replacement and support for various technologies. The build process in vidBuild involves optimizing and minifying assets, bundling JS and CSS, and generating chunks for dynamic imports. The pipeline in vidBuild includes plugins for alias, resolution, CSS modules, and asset handling. Vid is a complete build tool with a flexible plugin system and support from a vibrant community. Vite's plugin API is compatible with Rollup, and Vite aims for simplicity while pushing complexity to the plugin system.

1. Introduction to vidBuild

Short description:

Welcome to vidBuild. We will explore how vidBuild optimizes your application for production. Vid offers lightning-fast hodgemodule replacement, out-of-the-box support for Typescript, JSX, PostCSS, CSS modules, and more. It shines when building your application for production. Try it out at vid.new/vue, play with the application, and experience the fast feedback loop. When ready to deploy, use fit build to bundle your app with rollup.

Welcome to vidBuild. We are going to dive into the inner workings of the vidBuild process to understand how it bundles and optimizes your application for production. First a bit about me. I am Matias Capeleto, also known as Patak. I'm a Vid core team member and a Vitez core team member, which is a new Vid-native JS alternative. I'm also a Vue team member, and I now join the Stacklists team to work full-time on Vid and its ecosystem.

So, why Vid? When talking about Vid, we normally focus on its dev server. Vid doesn't bundle your app during dev, so the server starts instantly. Vid transforms your modules on demand over native ESM as the browser requests them. And doing so, it offers lightning-fast hodgemodule replacement that stays fast regardless of the app size. You also get out-of-the-box support for Typescript, JSX, PostCSS, CSS modules, and more, and a powerful relab-based plugin API to extend it. For example, to use Vue single file components, or other frameworks. But this is half of the story. Vid also shines when building your application for production, and this will be the focus of the talk.

First, let's try it out. You can go to vid.new slash vue in your browser and this will open a stacklit playground that is going to fork the vue starter in the vid repo. You can see that we can play with the application before we can finish explaining what is going on. Stacklit is running Node in the browser using web containers, giving us an experience that is almost the same as our local environment. The install size of vid is really small, so the install went really fast, and from there the vid server started right away as there is no need to bundle your application. The browser requested the index.html, encounter a script type module, and kept requesting the modules of your application. We can go to this first module, and you can see that there is an import for app.view. This is a view single file component, and the browser doesn't know how to process it. But in the vid.config.js, we have configure the plugin vid.js.plugin.view, and this lets vid understand single file components and give the browser the js and CSS that it understand. Let's go to hello world.view and modify it so we can see hot model replacement kick in. Let's change also some colors here, and you can see that as soon as we save, the change is reproduced instantly on the other side. The count is also maintained, the state is preserved. And this fast feedback loop is almost the same as the one you get when modifying something with the browser dev tools, and it's incredible to work like this during development. Let's close now the dev server. And when you're ready to deploy your application, you use fit build to bundle your app for production. Fit build uses internally rollup to bundle all the assets of your application.

2. Build Process and Internal Plugins

Short description:

By default, the assets are in the dist folder. The files are optimized and minified, and hashed for strong caching in the browser. Vite at build time configures rollup with feature plugins like PostCSS and JSON import. The build process starts with the index.html entry point, extracting scripts and CSS. JS and CSS assets are processed, bundled, and minified. Vite supports code splitting and generates chunks for dynamic imports. Other assets like images and videos are also processed. Vite uses the ROLAPplugins API to support features and optimization. During build, standard ROLAPplugins are used.

By default, they are in the dist folder. Here you can see in the assets that an index.js was generated and is now optimized and minified. And the same for the CSS. The same goes for an image that was imported and a vendor chunk was split by default. In the output index.html, we can see that we are now importing the index script and this script is going to import the vendor chunk. So to avoid the loading waterfall, we are pre-loading it here right away. And we are also linking the CSS stylesheet. All these files are hashed so they can be strongly cached in the browser.

If we want to check the bundled application, we can call vidpreview that is going to load in localhost directly the application to play with. And this is not using the VDev server, but directly the optimized application. Okay, let's move on.

So Vite at build time is an opinionated rollup setup. It gives you good default for the most common cases and configures rollup with feature plugins like support for PostCSS, JSON import, WASM, WorldCard and ads plugin to optimize your code like minification using ESBuild, code splitting, assets preloading, etc. The build process starts with the index.html entry point as we saw, which is parsed to extract the scripts and linking CSS or inline stylesheets. The script tags or imports coolpoint to TypeScript files or other file types as long as Vite knows how to transpile them or it is extended with user plugins to deal with them, as we saw with the Vue plugin. The same goes with the CSS. Both linked or inlined they will be extracted and processed by the pipeline.

Once the JS or CSS assets are processed by the pipeline and bundled, then each chunk is minified and we have to replace the original script and link tags with them to create the output index.html file for our app. As we saw, Vite hashes these files so strong caching in the browser and also a vendor chunk is being generated and preload. The same goes for CSS styles that will be bundled and optimized accordingly. Vite supports code splitting both for JS and CSS assets, also by default. When a dynamic import is encountered, an Async.js chunk and a CSS chunk are generated for it. The import call is then instrumented in the importer chunk to preload dependencies and wait for the correspondent CSS style sheet. Other assets like images, videos, wasm that are imported are also processed by the build pipeline. Let's go through the internal plugins pipeline to get a glimpse on what Vite does during build. The ROLAPplugins API allows Vite to support most out-of-the-box features and optimisation as independent plugins. Vite uses an extended version of this plugin API that works both in-depth and built, introducing new Vite-specific hooks, for example to extend the depth server or augment the hot module replacement boundaries. Most plugins from the ROLAP ecosystem are compatible with Vite. During build, we are dealing with standard ROLAPplugins, since the Vite depth server is not on the table. The most typical hooks that you will encounter when you are creating one are Resolve.id, which lets you resolve an import path, for example, we need to resolve package names to its location in Node modules.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Vite: Rethinking Frontend Tooling
JSNation Live 2021JSNation Live 2021
31 min
Vite: Rethinking Frontend Tooling
Top Content
Vite is a next-generation build tool that leverages native ES modules for improved performance. It eliminates the need for bundling and improves hot module replacement. Vite provides an opinionated default configuration while still allowing advanced customization through plugins. It is framework agnostic and can be used for React and other applications. Vite is being adopted by Next.js and Create React App, and integration with Nuxt 3 offers significant speed improvements.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Welcome to Nuxt 3
Vue.js London Live 2021Vue.js London Live 2021
29 min
Welcome to Nuxt 3
Top Content
Nux3 has made significant improvements in performance, output optimization, and serverless support. Nuxt Bridge brings the Nitro engine for enhanced performance and easier transition between Nuxt 2 and Nuxt Read. Nuxt 3 supports Webpack 5, Bytes, and Vue 3. NextLab has developed brand new websites using Docus technology. Nuxt.js is recommended for building apps faster and simpler, and Nuxt 2 should be used before migrating to Nuxt 3 for stability. DOCUS is a new project that combines Nuxt with additional features like content modules and an admin panel.
How Bun Makes Building React Apps Simpler & Faster
React Day Berlin 2022React Day Berlin 2022
9 min
How Bun Makes Building React Apps Simpler & Faster
BUN is a modern all-in-one JavaScript runtime environment that achieves new levels of performance. It includes BUN dev, a fast front-end dev server, BUN install, a speedy package manager, and BUN run, a fast package runner. BUN supports JSX, has optimized React server-side rendering, and offers hot module reloading on the server. The priorities for BUN include stability, node compatibility, documentation improvement, missing features in BUN install, AST plugin API, native Windows support, Bundler and Minifier optimization, and easier deployment to production. BUN's AST plugin API allows for bundle-time JavaScript execution and embedding code, potentially inspiring new frameworks.
Turbopack. Why? How? When? and the Vision...
React Day Berlin 2022React Day Berlin 2022
32 min
Turbopack. Why? How? When? and the Vision...
The Talk discusses TurboPack, a successor to Webpack, aiming to create a framework-independent, flexible, and extensible tool for the open-source community. It addresses performance challenges by integrating SWC into Next.js. The challenges with Next.js and Webpack include orchestration issues, backward compatibility constraints, and cache invalidation problems. TurboEngine and TurboPack provide constant performance in incremental builds, leveraging Rust's predictable performance and parallelism. The Talk also covers topics like dependency tracking, task graphs, cache invalidation, lazy asset graphs, and the integration of TurboPack with Next.js. The future plans involve reconfiguring Webpack and TurboEngine, moving computations to the cloud, providing insights into builds, and facilitating migration and integration with JavaScript projects.
The Core of Turbopack Explained (Live Coding)
JSNation 2023JSNation 2023
29 min
The Core of Turbopack Explained (Live Coding)
Tobias Koppers introduces TurboPack and TurboEngine, addressing the limitations of Webpack. He demonstrates live coding to showcase the optimization of cache validation and build efficiency. The talk covers adding logging and memorization, optimizing execution and tracking dependencies, implementing invalidation and watcher, and storing and deleting invalidators. It also discusses incremental compilation, integration with other monorepo tools, error display, and the possibility of a plugin system for Toolpag. Lastly, the comparison with Bunn's Builder is mentioned.

Workshops on related topic

Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.