DEV Community

Cover image for Vite.js: Build Faster Frontends
Zahra Sandra Nasaka for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Vite.js: Build Faster Frontends

TL;DR: Vite.js is a modern frontend build tool that significantly speeds development and improves performance. It offers features like instant server start, hot module replacement (HMR), and efficient bundling with Rollup, making it a strong alternative to traditional tools like Webpack.

The pursuit of speed and efficiency in frontend development is becoming paramount with the rapid technological advancement in recent years. High performance and productivity are essential from both technical and business perspectives when considering the high demand for near-instantaneous load times and seamless interaction in software apps. Developers are constantly burdened with complex configurations and slow build times as traditional build tools often fall short of these key requirements. This is where new build tools like Vite come into play.

What is Vite?

Vite is a relatively new tool for speeding up and simplifying the front-end development process. Traditional build tools are often designed to create a complete bundle of all your code in one go. This process can be slow and irritating. Vite gets around this by simply serving your code to the browser as ES native modules during development, which reduces initial load considerably and improves user experience.

In the development environment, Vite loads only the parts of your code that are necessary at any given moment. Whenever a change is made to the code, it will only update the relevant module using Hot Module Replacement (HMR) so that you can see the latest changes instantly in the browser without waiting for a full page reload. As such, this technique not only enhances overall development speed and lowers development cost but, perhaps most importantly, makes the development process less stressful, especially in the case of considerably large projects.

It uses Rollup to bundle your code into optimized files when it is time for production builds. This process minimizes the code and removes unwanted files from the production build.

Key features of Vite

Vite comes with various features that frontend developers can employ to significantly improve the build times with less effort. However, these three key features of Vite make a real difference.

Instant server start

One outstanding feature of Vite is its ability to cold start a development server very fast. Even though conventional build tools like Webpack and Parcel offer the same feature, they often require a lengthy initial bundling process before serving the app. As a result, it can make the developer experience frustrating with long wait times and more resource consumption. In the case of Vite, it separates the app modules into source code and dependencies. Vite then eliminates the need to pre-bundle the source code by serving it over native ESM and significantly improves the dev server start time.

Lightning-fast HMR (Hot Module Replacement)

HMR is essential for a smooth developer experience as it allows frontend developers to view changes, they make in real time without a full page reload. Otherwise, the bundler would have to rebuild the entire app again and again whenever an update is made. Thanks to the usage of native ES modules and granular updates, Vite’s HMR capability is exceptionally fast and reliable, even when compared to other similar solutions like the Create React App.

Effective build process

Vite uses Rollup, a powerful and flexible bundler that guarantees high performance, for production builds. It comes with techniques such as tree-shaking (Rollup removes unused code, reducing the bundle sizes), code-splitting (a process to break down the app into smaller and more manageable chunks to load them on demand), and lazy loading that helps Vite optimize the loading time in the production environment.

Why you should use Vite?

The key features discussed above collectively make Vite a major candidate for building more efficient and manageable frontends. Vite also supports modern JavaScript features, such as dynamic imports and async/await. It shows high efficiency with debugging by facilitating comprehensive error handling and source mapping.

So, with everything considered, why should you use Vite to develop front-end apps? Because it has:

  • Simple configuration: Vite’s configuration is simple and straightforward, minimizing the time and effort spent on setup and maintenance. It comes with almost minimal to zero configuration and support for custom configurations where needed.
  • Framework support: Seamless support by Vite extends not just to React but also to a range of other popular and widely-used frameworks, such as Vue, Qwik, Preact, Lit, and Svelte.
  • TypeScript support: Vite not only supports TypeScript, but it uses esbuild to transpile TypeScript into JavaScript, making the process faster by 20 to 30 times than vanilla TypeScript.
  • Modern web standards support: Vite adheres to modern web standards, especially by utilizing the native ES modules. It facilitates developers to use the latest syntax and capabilities to help them ensure that the code is scalable and maintainable.
  • A great developer experience and usability: Ease of use and understandability are vital when choosing technologies for development. On that note, Vite offers a great experience to the developers with simple configurations and immediate feedback with the help of HMR.
  • Enhanced performance: In addition to the above, Vite boasts high efficiency and performance with significantly fast build processes, minimal wait times, and smaller and highly maintainable bundles.
  • CSS code splitting: Vite extracts the CSS for each module into separate files and loads them only when the corresponding module is loaded. Thus, it helps prevent performance issues caused by unused CSS often during the initial load.

Vite vs. Webpack

The following comparison between Vite and Webpack will help you determine the difference in approach and performance:

  • Vite and Webpack are both framework-agnostic.
  • Vite is easier to learn and configure than Webpack, which is more complex. So, it is beginner-friendly and requires less effort when getting started.
  • Webpack contains extensive features and complex configurations that can be beneficial but also lead to slower performance, especially with large projects. But, Vite offers a more streamlined approach that is compatible with all sorts of projects with a special focus on performance and efficiency.

Vite and Webpack

Not just with Webpack, Vite delivers higher efficiency and speed when compared to other battle-tested tools like Parcel and Create React App.

Getting started with Vite

Creating a project with Vite is pretty straightforward.

Step 1: Initialization and setup

Use one of the following commands to create a new Vite project.

npm create vite@latest

yarn create vite
Enter fullscreen mode Exit fullscreen mode

It will prompt you to enter a name for your app and select a framework of your choice.

Enter your app name and select a framework

The following prompt will allow you to choose from TypeScript and JavaScript to continue development once the project is created.

Prompt to choose from TypeScript and JavaScript for project developement in Vite

Step 2: Navigate and install dependencies

Use cd to move to the project directory vite-sample-project and use the following command to install the project dependencies:

npm install
Enter fullscreen mode Exit fullscreen mode

Step 3: Run the development server

You can start the development server with:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Prompt to run development server

Visit the browser to find your app running on http://localhost:5173/.

Creating a React app with Vite

Congratulations! You just finished creating a new React app with Vite successfully! You can try the following setup to create the same app with Webpack to feel the difference for yourself.

Webpack implementation

You can set up a project using Webpack to get a clear understanding of how it differs from the Vite approach.

Step 1: Initialize the project

To create just the basic package.json file for your project, run the following command:

npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Install dependencies

Unlike with Vite, you have to manually install both React and Webpack-related dependencies manually, along with multiple plugins, just to get the app running.

npm install react react-dom 

npm install --save-dev webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env @babel/preset-react html-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Step 3: Add configuration files for Webpack and Babel

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    port: 9000,
    hot: true, // Enable Hot Module Replacement
  },
};
Enter fullscreen mode Exit fullscreen mode

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}
Enter fullscreen mode Exit fullscreen mode

You can start coding straight away once the dependencies are installed with a simple npm install in the previous approach with Vite. There is no need to configure Webpack, Babel, or any loaders manually like this, as Vite comes pre-configured with sensible defaults.

Step 4 – Create index files to get started

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App with Webpack</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
  return<h1>Hello, from React app with Webpack</h1> 
}; 
ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Your folder structure will reflect the following.

Create index files to get started

Step 5: Build and run

Finally, update the package.json file.

"scripts": {
  "start": "webpack serve"
}
Enter fullscreen mode Exit fullscreen mode

You can try npm run start to start the dev server.

Creating React app with Webpack

Webpack will take longer to build than Vite due to its bundling process. It is easy to feel the difference in speed, configuration complexity, and overall experience now that you have experienced setting up the same React app with both Vite and Webpack. Vite is capable of making the development process simpler and also reduces the time spent waiting on builds. Just a few simple commands and you have the project up and running with minimal manual configuration and significant performance.

GitHub reference

For more details, refer to the GitHub demo.

Conclusion

Vite is, without a doubt, the frontend development game changer. It delivers exceptional speed and hence improves performance along with the developer experience, regardless of the project size. With its commendable startup speed and a short feedback loop, Vite ensures developers can focus on what they do best: write code.

So, if you are planning to start a brand-new project or enhance an existing one, Vite would be a great option, as it has many plus points.

Thank you for reading!

Related Blogs

Top comments (0)