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.

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.

3. Vite Build Pipeline and Plugins

Short description:

The load hook lets us get the code for a certain id, and is useful to implement virtual modules. The transform hook gives us the opportunity to transpile the code of a module. The first plugin in the pipeline is the alias plugin. Then we have the user preplugins. The Vite Resolve plugin implements the resolution logic for PATH. The Vite CSS plugin gives us support for CSS modules, PostCSS and other CSS preprocessors. The Vite ES Build plugin transpiles CSS sources. Then we have a few Vite JSON, Vite WASM and Vite Worker. The Vite Asset plugin implements the handling for imported assets. We then have the Vite CSS POST plugin. The VIT built HTML plugin process the HTML entry points. There are a few plugins that allow handling of dynamic imports importMetaURL and globe imports. The vid ESbuild transpile plugin leverages ESbuild to compile shales to the configured targets and minify the bundle code. The vid manifest and vid SSR manifest plugins allow projects to generate metadata about the generated chunks.

The load hook lets us get the code for a certain id, and is useful to implement virtual modules, for example. These are modules that don't exist in the file system, but we load them on the fly. We generate the code for them on the fly. The transform hook gives us the opportunity to transpile the code of a module, for example, to strip the types, info or compile JSX. And with the render chunk hook, we can transpile each bundle chunk, for example, minifying it with ESBuild.

The first plugin in the pipeline is the alias plugin, and this is the official Rollout plugin alias, and that, as we saw, most Rollout plugins are compatible, and several of them are used directly in the internal pipeline of it. This plugin lets users configure a map of aliases, so common import paths can be more manageable, a good use case for the resolve ID hook. For example, like if there is a components alias that is resolved to this folder, the user will be able to write an import no matter what it is in the folder tree, always as a slash components slash vuto.vue, and the plugin alias is going to transpile it to the proper location.

Then we have the user preplugins. This is the first batch of user plugins. In Vite there is a single list of plugins, but an enforced flag lets users decide where this plugin should be inserted in the pipeline. The Vite Resolve plugin implements the resolution logic for PATH, like no package resolution. The Vite CSS plugin gives us support for CSS modules, PostCSS and other CSS preprocessors. The Vite ES Build plugin transpiles CSS sources, stripping types, and compiling CSS using ES Build. Then we have a few Vite JSON, Vite WASM and Vite Worker, these are feature plugins, that give us support for common patterns, like importing a JSON file as an object.

Here we can see that we can even import a root field of the JSON as a name in export, and this helps with tree shaking. Then we have the Vite Asset plugin, that implements the handling for imported assets. For example, an image can be imported, resulted in an URL that can be used as is in the app code, and Vite will encode the image as a base 64 URL below a configurable cell size limit as an optimization out of the box. We then have the Vite CSS POST plugin, that uses ES build to minify CSS, and it plays a role in transforming dynamic import, so it's related CSS is preloaded when the corresponding js.async chunk is requested.

The VIT built HTML plugin process the HTML entry points, replacing the scripts and style sheet with their bundle and optimized version as we saw before. There are a few plugins that allow handling of dynamic imports importMetaURL and globe imports. For example, importMetaGlobe let us import a set of modules from the file system using a globe pattern and this syntax is supported by the VIT build import analysis plugin which expanded as a list of regular imports. So we can see that here we are requesting all the shales files in the dir folder and this is going to be transformed by the build import analysis plugin into an expanded list with each dynamic import for all the files that are in that folder at build time. The vid ESbuild transpile plugin leverages ESbuild to compile shales to the configured targets and minify the bundle code. A few minor versions ago vid used it tarsier for minification by default but once ESbuild minification became mature enough it was switched as a default, greatly speeding up the build process. And this is also important in the philosophy of vid because vid will use the best tool that is available at the time and will switch internal tools as the ecosystem evolves. The vid manifest and vid SSR manifest plugins allow projects to generate metadata about the generated chunks that can be used to integrate vid with other tools, like rails or Laravel. For example, the vid manifest plugin generates a manifest.json file that contains a mapping of non-hashed asset file names to their hashed versions, which can then be used by a server framework to render the correct asset links. And this is the complete build pipeline of plugins and you can see that there are quite a few of them.

4. Complete Built Pipeline and Features

Short description:

Vid is an opinionated and complete build tool that offers a complete JavaScript API, instant feedback loop, and out-of-the-box support for TS, CSS, post CSS, and more. It provides a flexible plugin system that taps into and augments the ecosystem, allowing frameworks to use existing plugins or develop their own. Vid also offers a shared low-level SSR API and optimized build support using rollup, with the option for legacy browser support using VJ.

And this is the complete built pipeline of plugins and you can see that there are quite a few of them. If we will use plain rollup, we will have to configure it with an equivalent pipeline if we want to support all the features and optimization that vid offers. We can see that even without the VDev server on the table, vid has a lot of value as an opinionated and complete built tool because you get this out of the box. So vid is also an extendable toolkit to craft modern framework. There is a complete JavaScript API. As we saw there is instant feedback loop using dev and bundled modules, out of the box support for TS, CSS, post CSS and more. So frameworks don't need to care about how to support this. There is a flexible plug in system tapping into and augmenting the ecosystem. And this also lets framework use the plug ins that all the ecosystem is working on and also develop their own for their specific needs. There's a shared low-level SSR API that they can share, and out of the box support for optimized build as we saw using rollup. And if needed, there can be support for all browsers using VJ as plug in legacy.

5. VIT Projects and Community

Short description:

VIT has seen an explosion of projects using it, with support from various UI frameworks. The vibrant ecosystem of plug-ins and the community's collaboration have contributed to VIT's success. There are over 500 collaborators in the VIT repository, and the community actively reviews PRs. The core team consists of around 7 or 8 people, but there are many contributors from different frameworks. For PRs, fixed PRs require two approvals from core contributors, while new features are decided by the entire core team. Triage and community involvement are areas where help is needed.

So this ended up in an explosion of projects using VIT. First, the VIT core team maintains plug-ins for Vue and React, and the teams of Svelte, Preact, Solid, Marco, between others' UI frameworks provide Polish's official plug-in for each of them. There is also a vibrant ecosystem of plug-ins, and a complete list is maintained at awesome-vit. You can get plug-ins for BWA, or even to help in debugging, and a big part of VIT's success is due to it being chosen by modern app frameworks like SvelteKit, Knux 3, Hydrogen, Astro, Solid Start, just to name a few.

And that is all. You can continue digging deeper into how Vite Build is implemented at patak.dev.vite.build.html and you have the documentation at vites.dev or vitecore repo and the discord chat at chat.vites.dev and twitter handle is vites.js also. And if you are interested in Build tools and DX you should show in the Vite community and collaborate with us. We have a very welcoming community and a lot of collaborators working together to improve a ViteCore. That's nice.

So the question was about like if the people have participated before in the Vite community and yeah it looks like there is a lot of people that wants to do it. There was no answer about not wanting so it's a little bit tricky the question but that's that's good. Are you surprised with the results? Yes I saw that there will be some people answering about sending a PR. We have right now more than 500 collaborators in the Vite repository so I saw that some of them will be around. If you haven't done it like Vite is a really good project to get involved and like there is a very active, not only the community in this core. But also in the Vite Repo itself there is a lot of people reviewing the PRs and trying to to make things work so like... Do you have like first good issue or do you, I guess yes, you use standard labeling for your issues? Yes we don't use that much the good for issue label in particular we have like a lot of issues Vite kind of exploded the new Sash in the last year so we went actually to 77... 770 issues actually and now like we are trying to close as many as possible There is one of the collaborators that is doing an amazing job there so the best is just to get into triage like check any issue and check if it's still relevant like if it is a configured problem and then get into into the code base. I think like most most of the issues are are like good for for collaborators.

How many of you are part of the core team? Right now around 7 or 8 people are in the core team but we have like Vite is also being pushed by all the frameworks using it so like the Sveltefox, the Astrofox, like all the people in the Vue ecosystem also there is now like this Hydrogen framework in the React ecosystem that is also pushing it forward. So we have actually a lot of contributors around the ecosystem. It's huge. So to to have a PR merged do you need the approval from a particular set of contributors like core contributors? How we do it is that like for fixed PRs we are like with two approvals from core contributors. We are moving forward with them. We have like some people in the ecosystem that are experts in some parts of it like SSR or like other other parts that we count their vote as one approval also even if they are not core team members. And then for new features we usually meet every two weeks and get all the core team together like with everyone included and everyone and we decide what new features are going to go in or not. Matias, where do you need the most help to push this project forward? Where would you like to see people contributing? There is docs, there is the PRs like you said. I think the community is quite lively in the sense of people doing docs and talking about it in Twitter, for example. I think where we need help is in triage and that is a very good way to get involved as we discussed before. We have a lot of new issues and also maybe if you have experience with it, joining the community and helping others is one of the best things you can do. OK.

QnA

Q&A and Developer Story

Short description:

Vite's plugin API is compatible with Rollup, making it easy to use custom Rollup plugins. Moving from Create React App to Vite is not difficult, and there is a project called Webpack to Vite that can assist with the conversion process. Vite aims for simplicity and focuses on providing good defaults for web app development. The core team strives to keep Vite small and pushes complexity to the plugin system. The speaker's developer journey began with a background in electronic engineering and transitioned to programming, working on various projects and eventually getting involved with Vite and Vue 3.

It's also a very good way to get involved. Don't forget that you can ask Matias more questions. He's going to be in the speaker room. And also, do we have any questions right now coming from the audience? Let's check.

OK, well you can join Matias at any time right now. Oh, there is one by Rens for the win. How easy it is to use a custom rollup plugin with Vite? It's pretty easy. The Vite plugin API is compatible, in the most part, with Rollup. It is an extension of Vite, so most plugins in the rollup ecosystem actually work out of the box in Vite. There are some very specific hooks that you cannot use, but this is quite rare, so it should work out of the box.

Jay Reed is asking how difficult it is to move from Create React App to Vite, and if there is a documented process? There is a project that is called Webpack to Vite, that is quite interesting because you run it in your project and it will actually do the conversion, or try to do the conversion automatically, so I think that is a very good way also if it doesn't work because you're doing something very custom, you can see all the steps. But it's mainly about removing, for example, Webpack and adding Vite and changing a few config options, it's not a very difficult process.

Okay, that sounds like... yeah. Do you aim for simplicity? That's what it looks like that you are trying to make it simple to adopt. Yes, one of the things that Vite has, philosophy-wise, is trying to cater to a smaller, let's say, target than, for example, what Webpack was doing, that was, like, you can do whatever you want with Webpack. But Vite was more targeted about, okay, let's do the best we can for a web app, and trying to get good defaults for that use case. People are starting to use it for other things, like Electron, but that's not the core competency. We usually in core are trying to keep it as small and pushing as much as possible of that complexity out. Luckily we have the plugin system that is quite flexible. So, most of the time we don't need to reject something, we just need to say, look, you can do the same with the plugin. So we try to keep core small. Excellent. And I really love the story of the tool, but I also love the story of the developers behind it. Tell us about your developer story. Are you self-taught? Did you come from, like, a computer sciences background? How was your journey to this moment? I studied electronic engineering, but I ended up more on the programming side. Did some C++ at the beginning. Like, my initial open source experiences were with some C++ libraries. And then went to other projects, like, started to do a lot of web that was not open source, but started to work with some graphical engines, like moving things from the server to the client. And about, I think, like, two years ago, like, starting because of an open source project that was using Vite and using Vue 3, we started to get more involved.

Vite Development and Future

Short description:

I joined Vite at the right time when there was a lot of collaboration needs. I love the instant feedback feature of Vite, which allows for exploration and programming by exploring options. Vite is consolidating its core and adding new features to improve HTML and CSS. The ecosystem is growing with many projects using Vite, and frameworks are building on top of it.

And this was just about the time when Vite was starting to get off. So I joined Vite at the, let's say, the right time there, when there was a lot of collaboration needs. So that's my story when I started. But you were doing build systems before, or you went from frontend development? I was doing, like, web in general, like for a lot of years, my work was, like, actually, like, doing a graphical engine, like, some kind of, like, online corel experience in the web. But I was doing more web development, not build tools, in particular.

Okay. And what do you love the most about tooling in general? About Vite, in particular, I think, like, what really got me into it was, like, the instant feedback. So this idea of, like, seeing your changes as you are modifying stuff. Like, if for example, you have a slider to change a color or something, you can really have the same experience you have with the dev tools. You can have it directly in, like, in your real code, no? And that instant feedback, like, really enables some kind of, like, exploration and, like, programming by exploring the options that you have. And I think that is quite interesting and what got me there.

Yeah, I think this is an amazing time for web developers. For those of us who are doing web development, like, many years ago, the state of it right now, it's, yeah, you can't compare it. It's amazing. It's really DX focused and I hope it stays this way. Where do you see Vite in the next year? Where is it going? What do you want to accomplish? I think, in core, consolidation, like, continue to make it more solid and we have some interesting features, like, improving HTML, like, we are working right now, like, there will be like CSS source map that wasn't possible before. There is some, but mainly consolidation, where I see a lot of innovation is in the projects using Vite, so the ecosystem is growing a lot and as well as like Hydrogen, there's, there are so many, so many projects that are now, like, using Vite and I realising this year is going to be about that, about the frameworks using it. Do the framework core teams get in touch with you to, yeah, okay, so they try to build on top of it, right? Yeah, yeah, and they usually need, a lot of the features, new features in Vite have been because of, like, frameworks, also maintainers actually needing them, so they propose, they even do the PRs and they work with us. Okay, thank you so much, Matthias. Again, to all the attendees, they can continue to ask you questions on Discord, devops-talk-q&a, and yeah, let me hand over to Anuradha again.

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

JSNation Live 2021JSNation Live 2021
31 min
Vite: Rethinking Frontend Tooling
Top Content
Vite is a new build tool that intends to provide a leaner, faster, and more friction-less workflow for building modern web apps. This talk will dive into the project's background, rationale, technical details and design decisions: what problem does it solve, what makes it fast, and how does it fit into the JS tooling landscape.

Workshops on related topic

React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
WorkshopFree
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.