On this article, we’ll take a look at the best way to improve a frontend internet software from Webpack to Vite.

Vite is the newest frontend growth software to be having fun with an amazing progress in reputation and adoption. Simply try these downloads from npm tendencies within the picture beneath.

npm trends graph for Vite

Image source

This pattern is being pushed by a key idea on the coronary heart of Vite: developer expertise. In comparison with Webpack, Vite can supply significantly faster construct instances and scorching reloading instances throughout growth. It does this by profiting from trendy browser options akin to ES modules in the browser.

A Vite application loaded with script type module

Earlier than we dive into the method of migrating from Webpack to Vite, it’s price noting that the frontend growth panorama is repeatedly evolving, and Vite isn’t the one software within the highlight. esbuild is one other extremely quick JavaScript bundler and minifier that’s catching the eye of internet builders. And if you happen to’re on the lookout for a extra zero-config strategy, you may also wish to discover Parcel, which supplies a seamless expertise for a lot of builders.

Desk of Contents
  1. Considerations before Migrating to Vite
  2. Step 1: Installing Vite
  3. Step 2: Make package.json Changes
  4. Step 3: Out with webpack.config, in with vite.config
  5. Step 4: Plugins
  6. Popular Webpack Plugins and their Vite Equivalents
  7. Conclusion

Issues earlier than Migrating to Vite

Whereas Vite introduces many thrilling new options into your workflow, as with all new know-how there are drawbacks to contemplate. When in comparison with such a mature software as Webpack, the first consideration would be the ecosystem of third-party plugins.

There are dozens of core/official Webpack plugins, and lots of (probably 1000’s) of community-contributed plugins on npm which have been developed over the ten years that Webpack has been in use. Whereas plugin help for Vite is excellent, it’s possible you’ll end up within the scenario the place the plugin you depend on in your mission doesn’t have a Vite equal, and this might turn out to be a blocker in your migration to Vite.

Step 1: Putting in Vite

Step one emigrate your mission is to create a brand new Vite software and discover the software you’re migrating to. You’ll be able to boilerplate a brand new Vite app with the next:

npm create vite@newest

New Vite application console output

Then begin the event server like so:

npm run dev

Now, navigate to the displayed localhost URL in your browser.

Vite application running locally

Vite will create a listing containing the information pictured beneath.

Vite folder structure

Many of those might be acquainted to you and might be like-for-like replacements in your personal software.

Step 2: Make bundle.json Adjustments

To start utilizing Vite in your current Webpack mission, head over to the bundle.json of the Webpack mission you wish to migrate and set up Vite:

npm set up –save vite

Relying in your frontend framework, you might also wish to set up the framework-specific plugin:

npm set up –save @vitejs/plugin-react

You too can replace any construct scripts it’s important to use Vite as a substitute of Webpack:

"construct": "webpack --mode manufacturing","dev": "webpack serve",
++   "construct": "vite construct",
++  "dev": "vite serve",

On the similar time, uninstall Webpack:

npm uninstall –save webpack webpack-cli wepack-dev-server

Now run your growth script to strive it out!

npm run dev

Step 3: Out with webpack.config, in with vite.config

Until you’re extraordinarily fortunate, you’ll more than likely want to incorporate some extra configuration. Vite makes use of the vite.config.js file for configuration, which is essentially analogous to your current webpack.config.js file.

You could find the complete documentation for this Vite config on vitejs.dev, however a easy Vite configuration for a React app would possibly appear like this:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  },
})

Step 4: Plugins

Underneath the hood, Vite makes use of Rollup as its construct software, and you’ll add any Rollup plugins to Vite by putting in them with npm:

npm set up –save @rollup/plugin-image

`

Additionally add them into the plugins array your vite.config.js file:


import picture from '@rollup/plugin-image'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
      image(),
  ],
})

Common Webpack Plugins and their Vite Equivalents

Let’s subsequent take a look at some widespread Webpack plugins and their Vite equivalents.

HtmlWebpackPlugin -> vite-plugin-html

HtmlWebpackPlugin simplifies the creation of HTML information to serve your Webpack bundles. When you’re utilizing HtmlWebpackPlugin in your mission, Vite has the vite-plugin-html plugin, which supplies comparable capabilities. You’ll be able to set up it like so:

npm set up --save-dev vite-plugin-html

And import into your vite.config.js like so:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
  plugins: [
    react(),
    createHtmlPlugin({
      entry: 'src/main.js',
      template: 'public/index.html',
      inject: {
        data: {
          title: 'index',
          injectScript: `<script src="./inject.js"></script>`,
        },
    })
  ]
})

MiniCssExtractPlugin is a plugin for Webpack that extracts CSS into separate information. It creates a CSS file for every JavaScript file that incorporates CSS. It’s usually utilized in manufacturing environments to facilitate extra environment friendly loading of CSS. The good thing about that is twofold. Firstly, it permits CSS to be cached individually by the browser. Secondly, it prevents a flash of unstyled content, as CSS is not embedded within the JavaScript information and may thus be loaded in parallel with JavaScript, leading to quicker web page load instances.

In Vite, you need to use vite-plugin-purgecss:

npm set up --save-dev vite-plugin-html-purgecss

Use the plugin in your vite.config.js file like so:

import htmlPurge from 'vite-plugin-html-purgecss'

export default {
    plugins: [
        htmlPurge(),
    ]
}

CopyWebpackPlugin -> vite-plugin-static-copy

CopyWebpackPlugin is used to repeat particular person information or complete directories to the construct listing. Vite has an identical plugin referred to as vite-plugin-static-copy:

npm set up --save-dev vite-plugin-static-copy

Put the next code into vite.config.js:

import { viteStaticCopy } from 'vite-plugin-static-copy'

export default {
  plugins: [
    viteStaticCopy({
      targets: [
        {
          src: 'bin/example.wasm',
          dest: 'wasm-files'
        }
      ]
    })
  ]
}

DefinePlugin -> outline()

In Webpack, the DefinePlugin is used to exchange tokens within the supply code with their assigned values at compile time. This lets you create world constants that may be configured at compile time. In Vite, you possibly can obtain the identical impact utilizing the outline possibility in vite.config.js, so it’s possible you’ll not want a plugin:

export default defineConfig({
  outline: {
    'course of.env.NODE_ENV': JSON.stringify('manufacturing'),
  },
})

Conclusion

This has been a easy information to migrating a frontend Webpack software to Vite, together with among the hottest Webpack plugins.

In case your mission is a big, advanced one with an intricate construct course of, Webpack’s feature-rich and versatile configuration could also be nonetheless your best option.

When you’re migrating a smaller or reasonable mission, Vite does provides some compelling advantages. Its pace, each when it comes to the server start-up and scorching module substitute, can considerably enhance growth productiveness. The simplicity of its configuration will also be a welcome respite, and its being designed with native ES Modules and trendy framework compatibility in thoughts units it up properly for the longer term.

Transitioning from Webpack to Vite does require cautious planning and testing, significantly when contemplating plugin replacements or refactoring. However the rewards of this transfer could be substantial. Vite provides a quicker, leaner growth surroundings that may in the end result in a smoother and extra environment friendly growth workflow.

It’s at all times helpful to control the evolving panorama of instruments. As you proceed your journey, think about additionally exploring different trendy instruments like esbuild and Parcel to search out one of the best match in your mission wants.

Bear in mind, the software isn’t what issues most, however how you utilize it to realize your goals. Webpack, Vite, esbuild, and Parcel are all wonderful instruments designed that can assist you create top-notch internet initiatives, and one of the best one to make use of is determined by your particular wants and constraints.

If you wish to discover Vite additional, try our article the place we explore Vite through its source code.