Vite vs Webpack. When speed matters. 2023 update

What is Vite⚡?

Many developers heard about Vite, and almost everyone knows Webpack. Let's try to answer this question: What is really better in 2023: Vite vs Webpack?

Let's have a look at Vite first.

Vite is a Next Generation Frontend Tooling. It pronounced /vit/ , like "veet".

It has these fantastic features:

  • Instant Server Start

  • Lightning Fast HMR

  • Rich Features

  • Optimized Build

  • Universal Plugins

  • Fully Typed APIs

Vite Dev server

Vite dev server provides many enhancements over native ESM imports:

  • NPM Dependency Resolving and Pre-Bundling

  • Hot Module Replacement

  • TypeScript and TypeScript Compiler Options

  • Proxy

  • Vue/React/

  • JSX, CSS, JSON

  • Static Assets

  • Glob Import

NPM Dependency Resolving and Pre-Bundling

import { someMethod } from 'my-dep'

The above code will throw an error in the browser.

Vite does:

  • Pre-bundle them and convert CommonJS / UMD modules to ESM (ES module). The pre-bundling step is performed with esbuild, making Vite's cold start time significantly faster than any JavaScript-based bundler.

  • Rewrite the imports to valid URLs like /node_modules/.vite/my-dep.js?v=f3sf2ebd so the browser can import them correctly.

  • Cache dependencies via HTTP headers, so it will run pre-bundle only if some of these dependencies have been changed:

  • The dependencies list in your package.json.

  • Package manager lockfiles, e.g. package-lock.json, yarn.lock, or pnpm-lock.yaml.

  • Relevant fields in your vite.config.js, if present.

Hot Module Replacement (HMR)

Vite provides an HMR API over native ESM, which is much faster than Webpack.

  • Instant, precise updates without reloading the page or blowing away the application state.

  • First-party HMR integrations React Fast Refresh.

  • No configuration is needed.

  • It offers the best developer experience and fast page load

TypeScript

Vite supports TypeScript and TypeScript Compiler Options

  • Vite supports importing .ts files out of the box.

  • Vite does NOT perform type checking. You can use the TypeScript compiler to perform type checking. Usually, IDE takes care of it.

  • Vite uses esbuild to transpile TypeScript into JavaScript (about 20~30x faster than vanilla tsc, and HMR updates < 50ms).

  • Some configuration fields under compilerOptions in tsconfig.json require special attention.

  • isolatedModules should be set to true.

  • useDefineForClassFields should be set to true if the TypeScript target is ESNext.

JSX

JSX transpilation is also handled via esbuild and defaults to the React 16 flavour.

React 17 style JSX support in esbuild is tracked here.

CSS


@import Inlining and Rebasing

Vite is pre-configured to support CSS @import inlining via postcss-import.

It respects @import for CSS CSS url() references are always automatically rebased to ensure correctness.

PostCSS

If the project contains valid PostCSS config (any format supported by postcss-load-config, e.g. postcss.config.js), it will be automatically applied to all imported CSS.


CSS Modules

Any CSS file ending with .module.css is considered a CSS modules file. Importing such a file will return the corresponding module object:

 / example.module.css /
.red {
  color: red;
}
import classes from './example.module.css'  
document.getElementById('foo').className = classes.red

SS modules behaviour can be configured via the css.modules option.

If css.modules.localsConvention is set to enable camelCase locals (e.g. localsConvention: 'camelCaseOnly'), you can also use named imports:

// .apply-color -> applyColor  
import { applyColor } from './example.module.css'  
document.getElementById('foo').className = applyColor 

CSS Pre-processors

Vite does provide built-in support for .scss, .sass, .less, .styl and .stylus files. There is no need to install Vite-specific plugins for them, but the corresponding pre-processor itself must be installed:

# .scss and .sass  
npm add -D sass  
# .less  
npm add -D less  
# .styl and .stylus  
npm add -D stylus  

You can also use CSS modules combined with pre-processors by prepending .module to the file extension, for example, style.module.scss.

Static Assets

Importing a static asset will return the resolved public URL when it is served:

import imgUrl from './img.png'  
document.getElementById('hero-img').src = imgUrl  

Glob Import

Vite supports importing multiple modules from the file system via the special import.meta.glob function:

const modules = import.meta.glob('./dir/*.js') 

The above will be transformed into the following:

// code produced by vite  
const modules = {  
  './dir/foo.js': () => import('./dir/foo.js'),  './dir/bar.js': () => import('./dir/bar.js')}  

You can then iterate over the keys of the modules object to access the corresponding modules:

for (const path in modules) {  
  modules[path]().then((mod) => {    console.log(path, mod)  })}  

Matched files are by default lazy loaded via dynamic import and will be split into separate chunks during the build.

If you'd rather import all the modules directly (e.g. relying on side-effects in these modules to be applied first), you can use import.meta.globEager instead:

const modules = import.meta.globEager('./dir/*.js')  

The above will be transformed into the following:

// code produced by vite  
import * as __glob__0_0 from './dir/foo.js'  
import * as __glob__0_1 from './dir/bar.js'  
const modules = {  
  './dir/foo.js': __glob__0_0,  './dir/bar.js': __glob__0_1} 

Glob Import important info

  • This is a Vite-only feature and is not a web or ES standard.

  • The glob patterns are treated like import specifiers: they must be either relative (start with ./) or absolute (start with /, resolved relative to project root) or an alias path (see resolve.alias option).

  • The glob matching is done via fast-glob - check out its documentation for supported glob patterns.

  • You should also be aware that glob imports do not accept variables; you must pass the string pattern directly.

  • The glob patterns cannot contain the exact quote string (i.e. ', ", ) as outer quotes.

  • e.g. '/Tom\'s files/` , use "/Tom's files/" instead.

Optimized build with Vite.js

CSS Code Splitting

Vite automatically extracts the CSS used by modules in an async chunk and generates a separate file for it.

When the associated async chunk is loaded, the CSS file is automatically loaded via a <link> tag. The async chunk is guaranteed to be evaluated after the CSS is loaded to avoid FOUC (Flash of unstyled content).

If you'd rather have all the CSS extracted into a single file, you can disable CSS code splitting by setting build.cssCodeSplit to false.

Preload Directives Generation

Vite automatically generates <link rel="modulepreload"> directives for entry chunks and their direct imports in the built HTML.

Async Chunk Loading Optimization (Code-splitting)

When we build the production application, Rollup often generates "common" chunks - code that is shared between two or more other chunks. Combined with dynamic imports, it is pretty common to have the following scenario:

Vite chunk loading optimisationIn the non-optimized scenarios, when async chunk A is imported, the browser will have to request and parse A before it can figure out that it also needs the common chunk C. This results in an extra network roundtrip:

Entry ---> A ---> C 

Vite automatically rewrites code-split dynamic import calls with a preload step so that when A is requested, C is fetched in parallel:

Entry ---> (A + C)

Vite Plugins

Vite can be extended using plugins, which are based on Rollup's well-designed plugin interface with a few extra Vite-specific options.

This means that Vite users can rely on the mature ecosystem of Rollup plugins, while also being able to extend the dev server and SSR functionality as needed.

How to find Vite plugins

Visit the official plugins page

Adding Plugin

To use a plugin, it needs to be added to the devDependencies of the project and included in the plugins array in the vite.config.js config file. For example, to provide support for legacy browsers, the official @vitejs/plugin-legacy can be used:

npm add -D @vitejs/plugin-legacy
// vite.config.js  
import legacy from '@vitejs/plugin-legacy'  
import { defineConfig } from 'vite'  
  
export default defineConfig({  
  plugins: [
   legacy({
    targets: ['defaults', 'not IE 11']
   })
  ]})

Plugins also accept presets, including several plugins as a single element.

Migration to Vite from Webpack (React Create App)

Reasons

  • Development speed

  • Less complex than Webpack

  • Good support and documentation

  • Growing ecosystem

  • Many frameworks adapt Vite (Laravel, Storybook)

Total number of downloads between 2021-01-01 and 2022-07-16: +31,000,000

Migration Steps

1. Start with Vite local dev server. Keep Webpack as a build tool.

2. Use Vite (Rollup) for the production build of your app.

3. Use Vitest to run tests.

How to use Vite dev server

Install Vite and Plugins

npm i vite vite-plugin-env-compatible vite-tsconfig-paths vite-plugin-svgr --save-dev
  • @vitejs/plugin-react plugin for React projects

  • vite-tsconfig-paths plugin gives vite the ability to resolve imports using TypeScript's path mapping.

  • vite-plugin-env-compatible plugin inject to process.env like vue-cli or create-react-app and also define client "prоcess.env.XXX" for you. By default, Vite exposes env variables on the special impоrt.meta.env object.

  • vite-plugin-svgr plugin to import SVG files as React components using svgr under the hood.

Setup index.html file

Vite treats index.html as source code and part of the module graph.

We need to add another index.html file to the root directory with a script entry for your app:

<script type="module" src="/src/index.ts"></script>  

There's no need for special *%PUBLIC_URL%* placeholders unless you need injections.

In this case, you can use vite-plugin-html.

You can also use another folder than root if you specify in the config or as an option when you run

// package.json...  
"dev": "vite serve some/sub/dir --mode dev", 

Setup vite.config.js file

When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside the project root.

import { defineConfig, loadEnv } from 'vite'  
  
export default defineConfig(({command, mode})=>{  
  // Load env file based on `mode` in the current working directory.
  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
  const env = loadEnv(mode, process.cwd(), '')  
  return {    
    // vite config    
    define: {
      __APP_ENV__: env.APP_ENV
    }  
  }
})  

Enjoy the process: Vite vs Webpack benchmark

  • The first start (cold, no cache) can take from 1 to 5 sec (from my experience)

  • Other runs will take less than a second!

  • HMR will take 200-300ms!

My developer experience with Vite vs Webpack (JavaScript build tool)

Over the last 5 years, I have been working on more than 10 Vue projects. Initially, we used Webpack as a standard tool behind Vue CLI.

When Vite came out, we tried it on the new project and realised how fast it was.

We decided to move the biggest project to Vite next. This project had several thousand files (components, stores, pages, helpers).

With Webpack, even on my Mac with an M1 chip, it took 140+ seconds to start the app locally. After we switched to Vite, the cold start became about 3 seconds. The hot start became less than a second.

That was a really impressive result. We finished migration for the rest of our projects in a couple of sprints. Every new project since this time has always been powered by Vite.

What Issues have we encountered during the migration

  • Some libraries did not have proper ESM builds. We had to use early versions from contributors or contribute ourselves.

  • Webpack folder imports with require.context. We had to switch the implementation to use Glob Import from Vite.

How quick we migrated a project

It took about one month of work for 1 developer to migrate the biggest project, including experimenting and testing.

Stay up to date

Get notified when I publish New Games or articles, and unsubscribe at any time.

Thanks for joining!

FAQs

What is Webpack?

Webpack is a popular and versatile module bundler used for building JavaScript applications.

What makes Vite faster than Webpack?

Vite uses native ES modules and provides a faster and simpler build pipeline compared to Webpack's complex configuration process. Vite also only compiles what is used, reducing build times.

Why Vite is faster than Webpack

Vite is faster than Webpack because Vite uses native ES modules and provides a faster and simpler build pipeline than Webpack's complex configuration process.

Is Vite faster than Webpack

Yes, Vite is faster than Webpack.

When should I use Vite over Webpack?

Vite is recommended for small to medium-sized projects, where speed and simplicity are priorities. Webpack is better suited for larger, more complex projects.

Why is Vite faster than Webpack

Vite is faster than Webpack because Vite uses native ES modules and provides a faster and simpler build pipeline than Webpack's complex configuration process.

Is Vite better than Webpack

Most developers who tried Vite think Vite is better than Webpack.

Does Vite support hot module replacement like Webpack?

Yes, Vite supports hot module replacement and has similar features to Webpack.

Does Vite have a similar plugin system like Webpack?

Yes, Vite has a plugin system compatible with Rollup.

Is Vite production-ready?

Yes, Vite is production-ready and has been used in many production projects.

Can Vite be used with JavaScript frameworks like React or Vue?

Yes, Vite can be used with JavaScript frameworks like React and Vue.

What is Vite and Webpack?

Vite and Webpack are both front-end build tools that can be used for modern web development. They help take the JavaScript and CSS files and combine them into one bundle file that can be served to the browser.

What makes Vite different from Webpack?

Vite is a new breed of frontend build tool that significantly improves the frontend development experience by using modern web technologies to speed up the build process. It consists of two major parts: a dev server with rich features, and a build command that bundles your code with Rollup.

How does Vite work?

Vite works by using a dev server that runs your code with instant hot module replacement (HMR) for fast development feedback. When you are ready to build your project, Vite uses Rollup to create a production-ready bundle that is optimized for performance.

How does Webpack work?

Webpack works by using a similar build process to Vite, but it is known for its flexibility and configurability, which can make it more difficult to set up and use. Webpack is also a more mature tool than Vite, with a larger community and more plugins available.

What are the benefits of using Vite?

The benefits of using Vite are that it significantly improves the frontend development experience by providing a fast dev server with HMR, and a build process that is optimized for performance.

What are the benefits of using Webpack?

The benefits of using Webpack are that it is a highly configurable tool that can handle complex build processes, and it has a large community and ecosystem of plugins and libraries.

Can Vite be used for JavaScript and CSS projects?

Yes, Vite can be used for both JavaScript and CSS projects, and it has support for ES6 modules and other modern web technologies.

Can Webpack be used for JavaScript and CSS projects?

Yes, Webpack can be used for both JavaScript and CSS projects, and it has support for a wide range of web technologies and plugins.

How do I install and use Vite?

To install and use Vite, you need to have Node.js and npm installed on your computer. Then you can install Vite globally with npm, and create a new Vite project using the command-line interface.

How do I install and use Webpack?

To install and use Webpack, you need to have Node.js and npm installed on your computer. Then you can install Webpack globally with npm, and configure it using a webpack.config.js file in your project.

How does Vite speed up development?

Vite allows developers to create applications without the need for bundling during local development, which saves time and improves overall productivity. Additionally, Vite uses built-in caching for optimized performance when running builds.

How does Vite compare to other development tools like Webpack?

Vite is significantly faster than other tools like Webpack and Snowpack. It focuses on making development faster and more efficient by leveraging native ES Modules and HMR.

How does Vite handle the size of my application?

Vite is designed to handle front-end development environment for frameworks like Vue or React. It works well for smaller projects, but for larger applications, you may want to consider other tools like Webpack or Rollup for better application performance.

How can I use Vite to speed up my development process?

You can use Vite to create modern web projects faster by utilizing its rich features like HMR and built-in caching. Additionally, there are many Vite plugins available that can help you further improve your workflow and productivity.

Does Vite work with vanilla JavaScript?

Yes, Vite works with vanilla JavaScript as well as frameworks like Vue, React, and Angular.

How does Vite differ from other development environments for frameworks like Vue?

Vite is a development tool that focuses on speed and productivity, while other environments like Vue CLI focus on creating a complete development environment for building entire applications.

Can Vite be used for local development and for deploying to production?

Vite can be used for local development, but it is not recommended for deploying to production. For production, it is recommended to use a tool like Webpack or Rollup.

What is the difference between Vite and Webpack?

Vite is a faster and lighter dev server and bundler than Webpack, specifically designed for modern JavaScript frameworks like Vue and React. Vite takes advantage of ES modules in the browser to create a feedback loop that allows for faster development and hot reloading. Webpack, on the other hand, is a powerful bundler that can handle many different types of assets and is widely used in the JavaScript community.

Should I switch from Webpack to Vite for my production build?

It depends on your project and specific needs. While Vite offers faster build times and better performance gains, it may not yet have all the features and stability of Webpack. It’s best to test your project with both bundlers and see which one works better for you.

Can I use Vite for my existing Webpack project?

Yes, Vite can be used with existing Webpack projects. There are also Vite plugins available for popular frameworks like React, Vue, and Angular.

What is Snowpack and how does it compare to Vite and Webpack?

Snowpack is a new bundler that focuses on extremely fast build times and is written in Go. Snowpack is similar to Vite in that it uses ESM and can unbundle your JavaScript files to speed up build times, but it is not as feature-rich as Webpack.

Does Vite support Tree Shaking?

Yes, Vite supports Tree Shaking, which allows for smaller and faster bundles by removing unused code.

What is Storybook and how does it work with bundlers like Vite and Webpack?

Storybook is a UI development environment that allows you to develop and test UI components in isolation. Storybook is powered by bundlers like Vite and Webpack, and can be slow to start up or rebuild, so it’s important to optimize your Storybook performance with tools like cache and parallelism.

Do I need to run Babel with Vite?

No, Vite natively supports modern JavaScript features and does not require Babel. However, if you need to support older browsers or language features, you may still need to use Babel.

Does Vite replace Webpack?

No, Vite is not meant to replace Webpack entirely. While Vite may be a better fit for smaller projects or specific use cases, Webpack is still a powerful and widely used bundler in the JavaScript community. It’s ultimately up to the individual developer to decide which tool is best for their project.

What is the recommended use of Vite according to Medium?

Vite is recommended by Medium for smaller projects and projects with fast feedback loops. Medium suggests that for larger projects, it may be better to stick with Webpack.

What is the difference between Vite and Webpack’s configuration?

Vite does not have a dedicated configuration file like Webpack, whereas with Webpack, the configuration file can be very complex and extensive. Vite’s configuration is more minimal and relies on conventions and defaults to speed up development.

What is Vite?

Vite is a build tool for modern web development, introduced in 2020. It’s designed to be lightweight and fast, making it ideal for projects where speed matters. It uses es modules and transforms and serves code using native ES modules, without having to bundle them beforehand like Webpack.

How does Vite compare to Webpack?

Vite and Webpack are both build tools for JavaScript applications. However, Vite focuses on speed and simplicity, while Webpack emphasizes flexibility and configurability. Additionally, Vite is based on ES modules and native browser capabilities, which makes it faster than Webpack in some use cases.

Does Vite support all the features of Webpack?

No, Vite doesn’t support all the features of Webpack. For example, it doesn’t have loaders, but it does have plugins. Vite also doesn’t have the same level of configurability as Webpack, which may be a drawback for some users.

Can Vite be used with Create React App?

Yes, Vite can be used with Create React App. Vite offers a plugin that simplifies the process of integrating Vite into Create React App.

What is the recommended use case for Vite?

Vite is recommended for small to medium-sized projects, especially those that prioritize startup time and fast rebuilds during development. It’s also a good fit for projects that use ES modules extensively.

What is the recommended use case for Webpack?

Webpack is recommended for larger and more complex projects, where configurability and flexibility are critical. It’s a great fit for projects that require extensive customization and optimization for production performance.

Does Vite have better performance than Webpack?

Vite can have better performance than Webpack in some cases, especially for small to medium-sized projects. However, for larger projects, Webpack’s advanced features and configurability may give it an edge in terms of performance.

What is Storybook performance like with Vite?

Storybook performance with Vite is generally faster than with Webpack. Vite’s lightweight design and fast startup time make it ideal for Storybook, especially when dealing with many small components.

How does using Vite compare to waiting for Storybook to startup or rebuild with Webpack?

When using Vite, waiting for Storybook to startup or rebuild is generally faster than with Webpack. Vite’s hot module replacement (HMR) and native ES module support make it easy to update and rebuild components quickly.

Can Vite be used with Nest.js?

Yes, Vite can be used with Nest.js. Vite’s plugin for Nest.js simplifies the process of integrating Vite into Nest.js projects.

Related articles

Ruslan Osipov
Author: Ruslan Osipov