Saturday, September 16, 2023
HomeNodejsA Information to Migrating from Webpack to Vite — SitePoint

A Information to Migrating from Webpack to Vite — SitePoint


On this article, we’ll take a look at tips on how to improve a frontend internet utility from Webpack to Vite.

Vite is the newest frontend improvement software to be having fun with an amazing development in recognition and adoption. Simply try these downloads from npm developments within the picture beneath.

npm trends graph for Vite

Picture supply

This pattern is being pushed by a key idea on the coronary heart of Vite: developer expertise. Compared with Webpack, Vite can supply considerably quicker construct instances and scorching reloading instances throughout improvement. It does this by benefiting from fashionable browser options equivalent to ES modules within 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 value noting that the frontend improvement 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 searching for a extra zero-config method, you may additionally need to discover Parcel, which supplies a seamless expertise for a lot of builders.

Desk of Contents
  1. Issues earlier than Migrating to Vite
  2. Step 1: Putting in Vite
  3. Step 2: Make bundle.json Modifications
  4. Step 3: Out with webpack.config, in with vite.config
  5. Step 4: Plugins
  6. Fashionable 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 every 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 a whole lot (probably hundreds) of community-contributed plugins on npm which were developed over the ten years that Webpack has been in use. Whereas plugin assist for Vite is excellent, you could end up within the scenario the place the plugin you depend on on your undertaking doesn’t have a Vite equal, and this might change into a blocker on your migration to Vite.

Step 1: Putting in Vite

Step one emigrate your undertaking is to create a brand new Vite utility and discover the software you’re migrating to. You possibly can 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 will likely be acquainted to you and will likely be like-for-like replacements in your individual utility.

Step 2: Make bundle.json Modifications

To start utilizing Vite in your present Webpack undertaking, head over to the bundle.json of the Webpack undertaking you need to migrate and set up Vite:

npm set up –save vite

Relying in your frontend framework, you may additionally need 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 identical time, uninstall Webpack:

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

Now run your improvement script to strive it out!

npm run dev

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

Except you’re extraordinarily fortunate, you’ll almost certainly want to incorporate some further configuration. Vite makes use of the vite.config.js file for configuration, which is essentially analogous to your present webpack.config.js file.

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

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

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

Step 4: Plugins

Beneath the hood, Vite makes use of Rollup as its construct software, and you may 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(),
  ],
})

Fashionable 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. If you happen to’re utilizing HtmlWebpackPlugin in your undertaking, Vite has the vite-plugin-html plugin, which supplies comparable capabilities. You possibly can 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="https://www.sitepoint.com/webpack-vite-migration/./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 accommodates CSS. It’s sometimes utilized in manufacturing environments to facilitate extra environment friendly loading of CSS. The advantage of that is twofold. Firstly, it permits CSS to be cached individually by the browser. Secondly, it prevents a flash of unstyled content material, as CSS is now 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 whole directories to the construct listing. Vite has the same plugin known 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 interchange 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 may obtain the identical impact utilizing the outline choice in vite.config.js, so you could 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 utility to Vite, together with a few of the hottest Webpack plugins.

In case your undertaking 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.

If you happen to’re migrating a smaller or average undertaking, Vite does gives some compelling advantages. Its pace, each when it comes to the server start-up and scorching module substitute, can considerably increase improvement productiveness. The simplicity of its configuration may also be a welcome respite, and its being designed with native ES Modules and fashionable framework compatibility in thoughts units it up properly for the longer term.

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

It’s at all times helpful to control the evolving panorama of instruments. As you proceed your journey, take into account additionally exploring different fashionable instruments like esbuild and Parcel to seek out the very best match on your undertaking wants.

Keep in mind, the software isn’t what issues most, however how you employ it to realize your aims. Webpack, Vite, esbuild, and Parcel are all glorious instruments designed that will help you create top-notch internet tasks, and the very best one to make use of relies on your particular wants and constraints.

If you wish to discover Vite additional, try our article the place we discover Vite by way of its supply code.



RELATED ARTICLES

Most Popular

Recent Comments