The advent of build tools made many new innovations in frontend development possible. While tools such as webpack were at the forefront of this innovation, as time went by, they became slow and bloated. This made new build tools necessary — tools like Vite that were designed to be fast and lightweight.
In this guide, I will provide an overview of Vite, explain why you should use it, discuss what makes it better than its competition, explore its use cases, and more.
Build tools enable us to create complex user interfaces with multiple components, which were previously difficult or impossible to create with traditional HTML, CSS, and JavaScript. They also make it possible to minify and compress code, which improves the performance of web pages.
Additionally, build tools allow us to automate tasks such as code compilation and asset generation, which saves time and effort in the development process. Generally speaking, they make it possible for developers to create complex web applications with ease.
However, older build tools like webpack and Parcel were designed to work with large, complex applications. For smaller apps, they were overkill. While these older tools are still widely used, newer build tools like Vite and Snowpack have become the standard for building web apps.
Vite is a build tool and development server created by Evan You, the creator of Vue.js. Evan’s initial goal was to simplify and speed up the development and build processes for Vue applications.
Unexpectedly, Vite’s adoption surged, starting a new wave of innovation within the web framework ecosystem. Frameworks such as Nuxt 3, SvelteKit, Astro, Refine, Hydrogen, and SolidStart now use Vite by default. The React team also recently dropped its support for Create React App and recommends Vite’s create-vite
template instead.
Vite’s evolution continued with v2.0, which introduced significant changes such as a redesigned architecture and optimized performance and efficiency. This version also featured a new plugin system that enhances customization and extensibility in the development process, plus first-class support for CSS.
While Vite 2.0 introduced significant changes, the development team has continually improved on existing features while introducing new ones with every subsequent release.
The latest Vite 5.0 iteration leverages the updated Rollup module bundler and introduces a cutting-edge feature, server.warmup
. This feature allows us to specify a list of modules that should be pre-transformed as soon as the server starts, thus improving startup time.
Vite was created to improve DX by harnessing the capabilities of modern web technologies — such as native ES modules and esbuild — to speed up large-scale and modern web projects. This approach addresses issues with bundling and extended waiting times when initializing development servers.
Before ES modules, developers wrote code in formats such as CommonJS and AMD, relying on complex tools like webpack and Parcel to bundle this code. This involves concatenating multiple source modules and other assets into a single JavaScript bundle that can run in the browser using a dependency graph.
Unfortunately, as the application adds more code and dependencies, the bundling process becomes increasingly slow. This makes initializing development servers unbearably slow and even affects the feedback loop for hot module replacement (HMR) when changes are made in the application.
Vite mitigates this problem using ES modules and browser APIs, allowing developers to import and export modules directly without a complex bundling process. You can work with individual modules as separate files and leave the browser to handle how each module communicates, making the development process faster and more intuitive.
To improve the development server initialization time, Vite employs a unique technique that carefully segregates modules into two distinct groups:
Vite’s exceptionally fast development server is particularly well-suited for JavaScript-native application frameworks like Electron, which is known for its sluggish development server.
Vite’s blazing-fast development server, build customization, and other features make it a compelling choice for many developers. We’ll discuss its key features in detail shortly, but first, let’s review why I believe Vite is the future of frontend development and why you should use it.
The frontend DX basically revolves around the speed at which a developer can set up a dev environment and implement real-time changes. Even with project starters meant for quick setup, developers often spend a significant amount of time configuring essential development tools.
Vite checks all the boxes when it comes to this. It not only comes with pre-configured build settings out of the box but also offers a minimal-configuration setup and an extensive plugin system that encompasses all the necessary components for a development environment.
All of this, along with support for TypeScript, JSX, and CSS, makes it straightforward and efficient to initiate a web application development environment.
Providing support for a feature is important, but it’s not always enough. Accounting for edge cases is a whole other issue — but it’s one that Vite handles very well.
We discussed how shipping unbundled ESM isn’t efficient because of the additional network round trips caused by nested imports. Rollup and other build tools encounter similar issues when code-splitting with dynamic imports.
Rollup typically encounters this issue because it often produces a common chunk, or code that is shared between two or more chunks. When combined with a dynamic import, this can cause performance dips.
To provide a clearer picture, the Vite docs show the following visual representation of a common non-optimized scenario:
As shown in the image, when async chunk A is imported, the browser will have to request and parse this chunk before it can figure out if it also needs to request and parse common chunk C or not. This will result in an extra network round-trip:
Entry ---> A ---> C
Vite automatically rewrites every code-split dynamic import call with a preload step, which ensures that when async chunk A is requested, common chunk C is fetched in parallel:
Entry ---> (A + C)
As you may have already surmised, there is an additional edge case to consider here. In a non-optimized scenario, where the import depth is greater than what is shown in the example, there will be even more round trips. So, how does Vite deal with this?
It does so by precisely tracing every direct import and fetching them in parallel, thus eliminating further network round trips regardless of import depth.
This is a common issue in other build tools with similar features, but Vite automatically handles it for you without you having to worry about it.
As Vite loads async chunks, it automatically extracts the CSS used by modules in each chunk into separate files. These files are then loaded using the <link>
tag back to the associated chunk when it is loaded.
We’ll discuss this feature in more detail later, but essentially, this ensures that the CSS is only loaded when it is needed, which can improve performance. Additionally, Vite makes sure that each chunk’s CSS is loaded before it’s evaluated, thus preventing the dreaded flash of unstyled content (FOUC).
CSS code splitting is enabled by default. With this feature enabled, you don’t have to worry about unused CSS clogging up your application’s rendering pipeline in production.
Should you need to disable CSS code splitting, Vite provides the flexibility to do so by configuring the build.cssCodeSplit
option in your vite.config.js
file and setting it to false
. In this case, Vite will extract all the CSS in your project into a single file.
Vite’s out-of-the-box support for TypeScript is what I would consider the pièce de résistance of why many developers have migrated to Vite. Given the hassle of setting up TypeScript in a project, a tool that imports and transpiles .ts
files out of the box would be very appealing to most developers.
But Vite doesn’t stop there. It transpiles TypeScript into JavaScript using esbuild, which means that transpilation is 20 to 30 times faster compared to the vanilla TypeScript compiler. As a result, you can expect HMR updates to reflect in the browser in under 50ms. Yes, it is that fast.
Now that you know why I think you should use Vite, let’s discuss some of its drawbacks. To help you make an informed decision, I’ve listed below the pros and cons of Vite based on different aspects of web development:
Pros | Cons | |
---|---|---|
Dev workflow | Vite excels in providing a streamlined development workflow. Its instant server and fast HMR make development a pleasant experience, reducing the need for time-consuming rebuilds | Some developers might find Vite different from traditional bundlers, requiring an adjustment in their workflow |
Performance/speed | Vite is renowned for its exceptional performance. It leverages ES modules and efficient bundling techniques, resulting in rapid build times and a responsive development server | In huge projects, Vite’s performance benefits might not be as pronounced due to the inherent complexities of such projects |
Ease of use / DX / productivity | Vite is designed with DX in mind. Its simple configuration, quick setup, and immediate feedback loop enhance productivity | Developers transitioning from traditional bundlers might need some time to adapt to Vite’s unique approach |
Optimized code size | Vite supports tree shaking and code splitting, resulting in smaller and more optimized code bundles for production | Achieving optimal code size may require some configuration and fine-tuning |
Community & ecosystem | Vite has a growing community and a rapidly expanding ecosystem. It’s supported by the Vue team and has gained adoption in the broader JavaScript community | While Vite is gaining momentum, it might not have as extensive an ecosystem as more established tools like webpack |
Learning curve | Vite’s simplicity and intuitive setup make it relatively easy to learn, especially for developers with prior experience in web development | Developers entirely new to modern JavaScript tooling may still face a learning curve, but it’s less steep compared to some other tools |
Documentation | Vite’s documentation is comprehensive and well-maintained, providing clear guidance on how to use the tool effectively | As with any evolving project, there may be occasional gaps or updates in the documentation that require attention |
Integrations | Vite easily integrates with various front-end frameworks, libraries, and tools. It supports popular JavaScript frameworks like React, Vue, and Svelte, allowing you to seamlessly incorporate Vite into your existing project stacks | The level of integration with some less common or specialized tools might vary, requiring additional configuration |
As you can see, while Vite does have certain limitations, it’s a great tool with many benefits and features that can improve DX as well as application performance. Knowing its limitations and how they might affect your specific use case will help you work around them strategically and use Vite effectively.
We’ve discussed a few of Vite’s standout features in previous sections. Now, let’s dive into more of its key features in greater detail.
Vite and traditional bundle-based tools share one common feature: hot module replacement.
HMR is a dynamic process that allows a module to seamlessly replace itself without affecting the rest of the page, like updating a single piece of a jigsaw puzzle without having to redo the entire puzzle. This prevents the bundler from having to rebuild the entire application whenever something changes, which is a laborious task.
While HMR is a cutting-edge technique that greatly speeds up development by retaining an application’s state — which is lost during a full reload — the problem of progressive performance deterioration persists in most bundlers.
Vite solves this problem by performing HMR over native ES modules and letting the browser do most of the work. This means that Vite only has to invalidate the chain between the edited module and its closest HMR boundary.
In simpler terms, Vite marks the edited dependency modules as outdated and reloads them alone. This is faster and more efficient than reloading the whole page or all the modules, making it consistently fast regardless of the application’s size.
Vite uses Rollup to bundle your code for production. You may be wondering why it doesn’t use esbuild or ship directly to production since the browser supports ES modules natively. Comparing the pros and cons of Rollup and esbuild reveals the rationale behind the Vite team’s decision to use Rollup.
Firstly, esbuild is fairly new and doesn’t offer the same performance and flexibility tradeoffs as Rollup. The Vite team also believes that Vite would not be as popular without its adoption of Rollup’s plugin system.
Furthermore, shipping unbundled ESM in production is not efficient, as the additional network round trips caused by nested imports can quickly become an issue. You also lose out on features like tree shaking, chunk splitting, and lazy loading, which Vite uses to optimize loading performance in production.
Basically, Rollup has it all. Although it’s primarily known as the bundler tool that creates small and efficient bundles of code to improve performance, it is much more than that. Vite’s build customization options provide a testament to how powerful Rollup is:
vite build –watch command
, allowing you to have Vite rebuild your code whenever the vite.config.js
file changes, or when any code to be bundled changes. This can be useful for development, as it ensures that your code is always up-to-dateIn addition to these customizations, you can also customize Vite’s other settings, such as its port, watch options, and polyfills.
These strategies are reserved for advanced build configurations. However, Vite ships with a build setup that incorporates the necessary performance optimizations for simple applications. This build setup is run using the build
command, like so:
vite build
Vite features aren’t limited to what’s highlighted above. It also offers several other key features, including:
Lastly, since Vite is platform-agnostic, you can use it to develop web applications for various platforms, including traditional web browsers, Electron applications, and more. It’s a versatile tool that can adapt to different use cases and project requirements.
Vite is highly versatile and can be used for a wide range of business use cases, from simple statically generated pages to complex single-page and full-stack applications. Let’s explore some of the most common use cases for Vite, along with reasons why it is a good choice for each.
Admin panels and dashboards are examples of enterprise and B2B applications that tend to be data-intensive. These apps require proper optimization for their frontend workflows. Vite is the perfect web development tool for these kinds of applications.
For one, Vite’s hot reloading mechanism allows changes to code to be reflected in the browser almost immediately. This can save a lot of time when developing and debugging applications. Vite also supports code splitting, which can help improve the performance of these applications.
For content-driven websites like blogs, where page load speed is crucial for retaining readers, Vite’s rapid development server and efficient bundling can significantly improve UX. Faster load times mean readers can access articles more quickly and enjoy a smoother browsing experience.
Another use case for Vite is for building beautiful documentation sites using Vitepress, a static site generator built on Vite and Vue that uses Markdown and Vue components. Vitepress’s static site generation and efficient bundling can significantly improve UX as well.
Full-stack and decentralized applications are complex applications that require seamless integration between the frontend and backend. Vite’s flexibility and support for various front-end frameworks make it a solid choice for developing these types of applications.
Vite can easily integrate with backend technologies, contributing to the overall efficiency of the application. For an in-depth example, check out our Full-stack DApp tutorial with Vite + React, Tailwind CSS, and Solidity.
Vite’s fast development server and HMR make it perfect for quickly prototyping ideas and building minimum viable products. It allows developers to iterate rapidly, reducing time to market.
Vite is not a testing framework in itself, but it does incorporate a testing framework called Vitest.
Vitest uses Vite under the hood, which means that it inherits essential Vite features without any compatibility issues, including rapid feedback, minimal and sensible configuration, and optional chaining and nullish coalescing. This makes Vitest a powerful tool for ensuring code quality and developing test suites.
Vite is often compared to Create React App — so much so that the first few results you’ll get when looking up “Vite” on a search engine are likely to feature comparisons of both tools. However, this comparison is a misunderstanding, as Vite’s true counterpart is not Create React App.
Vite is a build tool, while Create React App specializes in generating preconfigured React templates. Vite does offer a CLI tool, create-vite, that lets you bootstrap templates for popular frontend frameworks and libraries.
A better comparison point for Vite would be tools like webpack and Snowpack, as they all function as build tools with similar purposes. Let’s delve into a comprehensive comparison of Vite, Snowpack, and webpack, considering their features, performance, community, and documentation.
Vite and Snowpack are quite similar, as they both leverage ES modules to speed up development and build times. They’re also both relatively simple to use, making them a good choice for beginners.
However, Vite has a few advantages over Snowpack. First, Vite is more versatile and supports a wider range of frontend frameworks, including Nuxt, React, Preact, and Svelte. Next, Vite has a plugin system that allows you to extend its functionality. Finally, Vite supports TypeScript out of the box.
On the other hand, webpack is a more powerful build tool than either Vite or Snowpack. It offers more customization options and can handle more complex projects. However, it is also more difficult to learn and lacks the flexibility and speed provided by Vite and Snowpack.
In terms of performance, Vite and Snowpack are standout choices for fast development.
Vite, using ES modules and esbuild, offers blazingly quick hot module replacement (HMR) and rapid initial builds. It’s ideal for projects demanding instant feedback. Snowpack also focuses on speed with ES modules, catering to smaller to mid-sized projects that require swift iteration.
On the other hand, webpack’s performance varies based on configuration complexity. While it can be optimized, it typically falls short of the rapid speeds provided by Vite and Snowpack. However, webpack excels at handling diverse and complex project requirements, making it suitable for large-scale applications.
Vite is a relatively new tool, and its community is not as established as, for example, webpack. However, its community is steadily growing, particularly within the Vue ecosystem. This growth is driven by active development and contributions.
Snowpack is also experiencing increased popularity, especially among developers seeking fast build times. However, it is no longer being maintained, and even its team recommends Vite as an alternative. Nonetheless, there are still a handful of developers who use Snowpack.
Meanwhile, webpack boasts a vast and seasoned community thanks to its widespread adoption and industry use. It offers extensive resources and a multitude of third-party plugins.
Vite offers comprehensive documentation that makes it easy for developers to get started. Its docs are well-organized and easy to follow, covering everything from basic usage to advanced topics. Vite also provides a range of tutorials and guides that can help users learn how to use the framework effectively.
Snowpack provides clear and concise documentation to help developers kickstart their projects. While not as extensive as webpack, Snowpack’s documentation equips users with the essential information needed to work efficiently.
Additionally, Snowpack’s active community contributes to the availability of resources and support. However, remember that the project is no longer actively maintained by its core team.
In comparison, webpack stands out with its extensive documentation and a wealth of third-party resources. The sheer number of tutorials and solutions available for webpack makes it a robust choice for developers seeking in-depth guidance and solutions for various scenarios.
The following comparison table summarizes the similarities and differences we’ve discussed for Vite, Snowpack, and webpack:
Vite | Snowpack | webpack | |
---|---|---|---|
Features | ES modules, HMR, out-of-the-box TypeScript support | ES modules | HMR and extended TypeScript and other feature integration through plugins |
Framework support | Framework-agnostic | Focus on React, Vue and Svelte | Framework-agnostic |
Extensibility and customizability | Flexible; has a plugin system for extending functionality | Offers a plugin-based architecture | Robust plugin ecosystem |
Learning curve | Easy to learn | Easy to learn | More difficult to learn |
Performance | Extremely fast and performant | Fast development and build times | Slightly slower due to more extensive features |
Community | Relatively newer and smaller, but active and steadily growing | Has an active and supportive community, but is no longer maintained by its core team | Vast and well-established |
Documentation | Comprehensive, well-organized, and easy to follow | Clear and concise, but not extensive | Extensive, both in terms of official docs and third-party resources |
Best for… | Projects of any size that require instant feedback | Smaller to mid-sized projects | Diverse, complex, and large applications |
create-vite and Create React App are tools for bootstrapping web development projects, but they cater to different ecosystems and have distinct characteristics. They do this by scaffolding code that includes the necessary libraries and frameworks for building a modern web application.
Using these tools can save developers a lot of time and effort, as they don’t have to start from scratch each time they create a new project. Here’s a quick overview of how they compare.
create-vite is a versatile project generator tool designed for speed:
Create React App provides a solid foundation for building React applications complete with service workers, testing setup, and more:
The choice between create-vite and Create React App depends on your project requirements and preferences. If you’re more focused on performance optimization and versatility, create-vite is probably the way to go. Meanwhile, Create React App offers a well-established, React-specific solution with an abstraction layer.
At the end of the day, the choice of the right tool depends on its compatibility with the specific use case, regardless of its flaws. This is precisely why tools like webpack continue to have a significant presence in the development ecosystem, despite the existence of superior alternatives such as Vite.
Switching to new tools can be challenging, as there is no guarantee that they will be maintained in the long term. Snowpack is an example of a tool that was discontinued, although this was reportedly due to burnout rather than technical reasons.
Vite, on the other hand, has grown to a point where it is unlikely to be discontinued, as it has a large community of backers and maintainers who are constantly working on it.
Each tool has its unique strengths and weaknesses and is tailored to meet a wide range of project requirements, from the established reliability of webpack to the unrivaled performance of Vite. Ultimately, to decide which tool to use, make sure you thoroughly assess the specific needs and constraints of your project.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBackdrop and background have similar meanings, as they both refer to the area behind something. The main difference is that […]
AI tools like IBM API Connect and Postbot can streamline writing and executing API tests and guard against AI hallucinations or other complications.
Explore DOM manipulation patterns in JavaScript, such as choosing the right querySelector, caching elements, improving event handling, and more.
`window.ai` integrates AI capabilities directly into the browser for more sophisticated client-side functionality without relying heavily on server-side processing.