Frontend Development 15 min read

Webpack vs Vite: Principles, Setup, and Hot Reload for Vue Projects

This article explains why Vite builds projects faster than Webpack by detailing their underlying mechanisms, step‑by‑step configuration of Webpack for Vue, the creation of a custom bundler, and how Vite achieves on‑demand loading and hot module replacement.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Webpack vs Vite: Principles, Setup, and Hot Reload for Vue Projects

Introduction

Creating a project with Vite is almost instantaneous, while using Vue‑CLI (Webpack) can take a noticeable amount of time; this article clarifies the reasons behind Vite's speed advantage over Webpack.

1. Basic Usage of Webpack

1.1 Directory Structure

Initialize a Vue project, then install webpack and webpack-cli globally.

yarn add webpack webpack-cli -g

Create the necessary Vue source files and a webpack.config.js configuration file.

1.2 webpack.config.js

Refer to the official Chinese documentation for configuration options, then start writing the config file.

(1) Bundle main.js

const path = require('path');
module.exports = {
  mode: 'development', // development mode
  entry: path.resolve(__dirname, './src/main.js'), // entry file
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].js' // default filename main.js
  }
};

Add a script in package.json to run the build:

"dev": "webpack server --progress --config ./webpack.config.js"

Running the command creates a dist folder and confirms that the bundle succeeded.

(2) Bundle index.html

Install html-webpack-plugin to handle HTML files:

yarn add html-webpack-plugin -D
const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, 'index.html'),
    filename: 'index.html',
    title: 'Manual Vue Setup'
  })
];

The resulting dist/index.html is generated successfully.

(3) Bundle Vue Files

Install Vue source and related loaders:

yarn add vue yarn add vue-loader@next yarn add vue-template-compiler -D
const { VueLoaderPlugin } = require('vue-loader');
module: {
  rules: [
    { test: /\.vue$/, use: ['vue-loader'] }
  ]
},
plugins: [new VueLoaderPlugin()]

After adding the loader, the Vue component compiles and the bundle runs correctly.

(4) Bundle CSS

Install CSS loaders to process .css files:

yarn add css-loader style-loader -D
module: {
  rules: [
    { test: /\.css$/, use: ['style-loader', 'css-loader'] }
  ]
}

After configuring, CSS is injected into the page as expected.

(5) Configure Babel

Install Babel to transpile modern JavaScript:

yarn add @babel/core @babel/preset-env babel-loader -D
module: {
  rules: [
    { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] }
  ]
}
module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { browsers: ['last 2 versions'] } }]
  ]
};

2. Webpack Bundling Principle

The bundling process consists of three main steps:

Read the entry file using fs .

Parse the entry file into an AST with @babel/parser , recursively collect dependencies, and generate an AST for each module.

Traverse the AST with @babel/traverse , transform code with @babel/core and @babel/preset-env , and finally emit a single bundle that mimics a require function.

A minimal custom bundler ( bundle.js ) is provided that reads files, builds a dependency graph, and outputs a self‑executing bundle using eval .

3. Vite Bundling Principle

Vite leverages native ES modules in the browser. When a <script type="module"> imports a module, the browser sends HTTP requests for only the modules actually used. Vite intercepts these requests, transforms the code on‑demand, and serves them, dramatically reducing start‑up time.

3.1 Problems Vite Solves

In a Vue project, the browser cannot resolve:

import { createApp } from 'vue';
import App from './App.vue';
import './index.css';

Vite addresses these three issues by providing module resolution, Vue SFC compilation, and CSS handling.

3.2 Building a Simple Vite Server

The following server.js uses Koa to serve files, rewrite import statements, and compile Vue SFCs on the fly:

const Koa = require('koa');
const app = new Koa();
const fs = require('fs');
const path = require('path');
const compilerDom = require('@vue/compiler-dom');
const compilerSfc = require('@vue/compiler-sfc');

function rewriteImport(content) {
  return content.replace(/ from ['"]([^'\"]+)['"]/g, (s0, s1) => {
    if (s1[0] !== '.' && s1[0] !== '/') {
      return ` from '/@modules/${s1}'`;
    }
    return s0;
  });
}

app.use(ctx => {
  const { request: { url, query } } = ctx;
  // ... (routing logic for HTML, JS, @modules, .vue, .css) ...
});

app.listen(5173, () => {
  console.log('listening on port 5173');
});

3.3 Vite Hot Module Replacement (HMR)

Vite uses chokidar to watch source files and a WebSocket connection to push update notifications to the browser. When a file changes, the client requests the updated module and applies the changes instantly.

const chokidar = require('chokidar');
export function watch() {
  const watcher = chokidar.watch('../src', {
    ignored: ['**/node_modules/**', '**/.git/**'],
    ignorePermissionErrors: true,
    disableGlobbing: true
  });
  return watcher;
}

export function handleHMRupdate(opts) {
  const { file, ws } = opts;
  const shortFile = getShortName(file, appRoot);
  const timestamp = Date.now();
  let updates;
  if (shortFile.endsWith('.css')) {
    updates = [{ type: 'js-update', timestamp, path: `${shortFile}`, acceptPath: `${shortFile}` }];
  }
  ws.send({ type: 'update', updates });
}

Conclusion

Webpack bundles all modules into a single file, which can be slow, while Vite serves modules on demand using native ES imports, resulting in a much faster development experience despite some minor drawbacks.

If this article helped you, feel free to follow, like, and bookmark it.

VueWebpackDevtoolsbundling
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.