Send your request Join Sii

Before the introduction of ES modules in browsers, JavaScript developers did not have a native way to write modular code. This led to the concept of bundling – using tools to process and combine source modules into files ready to run in the browser. Over the years, tools like Webpack, Rollup, and Parcel have significantly improved the work of front-end developers. However, as application demands grew, new challenges emerged.

Large projects can contain thousands of modules, leading to significant performance issues: long development server startup times and file update delays. These problems negatively impact developer productivity and satisfaction.

What is Vite?

Vite is a modern tool that aims to solve these issues by leveraging the latest advancements in the JavaScript ecosystem, such as native ES modules in browsers and tools written in languages that compile machine code, like Go.

Vite provides instant startup for development servers and fast module updates, regardless of application size. Vite is becoming an indispensable tool for modern front-end developers thanks to these innovations.

What do we need to start working with Vite?

Let’s begin by setting up our environment to work with Vite version 5. You will need:

  • Node.js version 18 or higher,
  • npm (Node Package Manager) to run scripts (or Yarn, Bun).

To check if you have the necessary software installed on your system, run the following commands one by one:

node -v i npm -v

You can easily install it on your machine if you do not have it installed.

Creating a new project

To create a new project, open your terminal and follow these steps:

  1. Run the following command to start creating the project:
npm create vite@latest
  1. Optionally, if prompted to install packages, type “y” and press enter.
  2. Enter the name of your project and confirm by pressing enter.
Select a framework
  1. Choose the technology you want to use for your application.
  2. After selecting the technology, you may need to choose a specific variant, such as the programming language you’ll use for your application:
Select a variant
  1. Once the packages are installed, run the following script to navigate into the project, install the necessary packages, and start the development server:
cd my-project
npm i
npm run dev
VITE v5.3.4

After a few seconds, you will receive information about which port your application is running on.

What does Vite offer?

Now that we know how to set up our first application using Vite, it’s time to explore the features that Vite provides.

Hot Module Replacement (HMR)

Vite offers an HMR (Hot Module Replacement) API based on native ESM (ECMAScript Modules). This allows projects with built-in HMR support to deliver instant and precise updates without reloading the page, preserving the application state and accelerating development.

What are the advantages of HMR in Vite over Webpack?

  • Speed – Vite uses esbuild for transforming and building dependencies, which is significantly faster than traditional JavaScript-based bundling tools.
  • Native ES Modules – Vite leverages native ES Modules supported directly by browsers, eliminating the need for additional bundling and enabling more efficient dependency management.
  • State Preservation – HMR in Vite maintains the current application state during module replacement, which is crucial for efficient and rapid debugging and development.
  • Simplicity and Convenience – Vite automatically configures HMR for popular frameworks, simplifying the process of creating new projects.

Pre-building and NPM dependencies

Native ES imports do not support the module imports commonly used in most projects. Since this would cause an error in the browser, Vite scans all such imports and performs the following actions:

  1. Pre-bundling – to speed up the application, it converts CommonJS modules to ESM. This process is handled by the esbuild bundler, which significantly accelerates application startup.
  2. Rewrites Imports to URLs – for example, Vite rewrites imports to something like “/node_modules/.vite/deps/my-dep.js?v=f3sf2ebd,” allowing the browser to import the file.

Additionally, to expedite this process, Vite uses a cache to remember previously imported files, so it doesn’t need to fetch them from the server again.

TypeScript code transpilation

Vite processes .ts files through transpilation but does not perform type checking. Vite assumes that type checking is handled by the IDE and the project’s build process.

Why doesn’t Vite perform type-checking? Transpilation and type-checking are two distinct processes:

  • Transpilation – processes each file individually, which aligns perfectly with Vite’s on-demand compilation model.
  • Type Checking – requires analysis of the entire module graph, which would slow down Vite.

Vite focuses on rapidly processing modules to get them running in the browser quickly. Therefore, it’s recommended that static analysis tools, such as ESLint, be run separately.

Additional features

We’ve already discussed the key aspects that make Vite stand out with its speed. However, it’s also worth mentioning that other benefits, such as those of different tools such as Webpack, are also supported here.

JSON import

JSON files can be directly imported into your code and utilized.

Static assets

Importing static assets will return a URL after the asset is served, allowing easy use in your application.

Dynamic imports

In addition to global imports, Vite also supports dynamic imports using variables. This functionality is similar to global imports but operates a bit differently. It’s important to note that dynamic import variables represent only file names at a single level of directory depth. This means the import will fail if a variable contains a path to a file within a subdirectory.

It is recommended to use the global import function for more complex scenarios requiring access to files in deeper directory structures. This method offers greater flexibility and capabilities for managing imports in more extensive projects.

CSS

Vite allows CSS files to be imported and injected into the <style> tags, enabling HMR and speeding up the application build process. Additionally, Vite supports various technologies and methods for writing styles, such as CSS Modules, PostCSS, and preprocessors.

Plugins

Just like Webpack, Vite allows for extending its functionality with additional plugins. These plugins are based on Rollup, enabling developers to use a rich ecosystem of ready-made solutions. For example, with plugins, you can enhance the functionality of the development server or implement Server-Side Rendering (SSR) in your project.

Below is a sample code snippet that demonstrates how to implement SSR in your project using the vite-plugin-ssr/plugin plugin:

import

As you can see, adding SSR support to your project has never been easier.

Performance

Vite is a tool that takes care of application performance right from the start. However, as project requirements grow, it’s worth paying attention to a few key aspects.

For this article, let’s draw some insights from a blog post by another developer: Is Vite Really Faster Than Webpack? Specifically, we’re interested in the application he created and shared on GitHub. He prepared a small project comparing build times and browser load times depending on whether Vite or Webpack is used and how many components are in the application. Below, I’ve included an image provided by the author.

Comparision of Vite and Webpack
Fig. 1 Comparision of Vite and Webpack

As you can see, Vite has a significant advantage, at least in the beginning. However, as the number of components increases, the application’s load time in the browser extends significantly, favoring Webpack. The post’s author suggested using lazy loading to solve the load time issue.

After implementing this, the build and load times decreased drastically, which shouldn’t be surprising, but once again, Vite proved to be faster than Webpack.

Other tips

What else can affect server start time, page load time, or application build time?

Careful selection of plugins

Vite allows for the use of plugins provided by the community, which creates its solutions as needed. While these can often make work more accessible, they are beyond the control of the official technology creators. They suggest that when choosing a plugin, you should consider the following:

  • significant dependencies that are rarely used should be imported dynamically to shorten Node.js startup time,
  • avoid long-running operations in the buildStart, config, and configResolved hooks, as these delay the start of the development server.

Avoid barrel files

What are barrel files? Barrel files are a way to export all the code from a directory through an index.js file. For example:

//index.ts

When importing the helper1 method, you’re also pulling in the other two methods (helper2 and helper3), which take up memory and might contain side effects. In summary, you’re importing code that you don’t need, which can reduce performance.

Managing styles

Another recommended method for improving performance is to use native solutions when styling and adding graphics. The recommendations include:

  • Use CSS instead of preprocessors where possible. For nesting, PostCSS is useful.
  • Avoid importing SVGs as components. Instead, use them as strings or import them via URL.
  • When using the vitejs/plugin-react plugin to work with React, avoid configuring Babel unless necessary.
  • Consider using the LightningCSS parser for styling, as it can offer better performance.

Specify the file extension when importing

Importing files in Vite can be crucial from a performance perspective, particularly regarding file extensions. Vite allows you to import files without specifying their extensions. However, here’s how it works. When you import a file, e.g., Test. tsx with the path ./components/Test, Vite starts searching for the specified file in the following order:

  1. Test
  2. Test.mjs
  3. Test.js
  4. Test.mts
  5. Test.ts
  6. Test.jsx
  7. Test.tsx
  8. Test.json

As you can see, if you want to import a JSON file, Vite will need to go through several steps to check if the file exists in the folder. Instead, it’s recommended that the file be imported along with its extension. In our case, it would be ./components/Test.tsx. This approach reduces the time Vite spends searching for the correct file, improving overall performance.

Summary

We’ve explored the fundamental advantages of Vite. The natural question for any developer is: “Can Vite replace Webpack?” As always, the best answer is: “It depends.” 😉

It would certainly be appealing to use Vite for a new project that you’re starting from scratch. However, the reality of a developer’s life is not always so ideal. Often, we have to deal with legacy projects where many packages are configured for the stable, long-standing tool Webpack. Migrating an application to Vite could be pretty challenging and problematic.

If you are new to the IT world or are starting a new project, Vite appears to be an excellent tool with which to experiment. It is straightforward to configure, and its HMR (Hot Module Replacement) feature is a fantastic solution that accelerates development. Starting a project with Vite involves just a few steps in the terminal, and voilà, you’re ready to begin development.

It’s worth watching how this technology evolves because it has significant potential. However, its potential also heavily depends on the number of users, developers, and plugins that support and enhance Vite.

I highly encourage exploring this technology and seeing how it fits into your development workflow 😊

***

If you are interested in the tools used in IT, be sure to also take a look at other articles by our experts.

5/5 ( vote: 1)
Rating:
5/5 ( vote: 1)
Author
Avatar
Filip de Tillier

A graduate of the Gdansk University of Technology. In 2017, he started his professional career mainly as a Front-end developer. He also has experience as a Back-end developer using JavaScript and Python. He is currently focusing on development in the React library. His passion is sports and F1

Leave a comment

Your email address will not be published. Required fields are marked *

You might also like

More articles

Don't miss out

Subscribe to our blog and receive information about the latest posts.

Get an offer

If you have any questions or would like to learn more about our offer, feel free to contact us.

Send your request Send your request

Natalia Competency Center Director

Get an offer

Join Sii

Find the job that's right for you. Check out open positions and apply.

Apply Apply

Paweł Process Owner

Join Sii

SUBMIT

Ta treść jest dostępna tylko w jednej wersji językowej.
Nastąpi przekierowanie do strony głównej.

Czy chcesz opuścić tę stronę?