DEV Community

Tianya School
Tianya School

Posted on

Vite: A quick guide to the next generation front-end building tool

Vite is a next-generation front-end build tool developed by Yuxi You, the author of Vue.js. It has attracted widespread attention for its fast cold start, on-demand compilation, and hot update capabilities. Vite provides almost instant development environment startup speed and highly optimized development experience by leveraging the browser's native ES module import function.

Install Vite

First, make sure Node.js is installed in your system (LTS version is recommended). Then, install Vite globally through npm or yarn:

npm install -g create-vite
# Or use yarn
yarn global add create-vite
Enter fullscreen mode Exit fullscreen mode

Create a new project

Use the create-vite command to create a new Vite project. Here is an example of creating a Vue project:

create-vite my-vite-project --template vue
cd my-vite-project
Enter fullscreen mode Exit fullscreen mode

This will initialize a Vue 3-based Vite project.

Development and running

In the project root directory, run the following command to start the development server:

npm run dev
# Or use yarn
yarn dev
Enter fullscreen mode Exit fullscreen mode

Vite will immediately start a local development server, and you can visit http://localhost:5173 in the browser to view your application. Vite supports hot module replacement (HMR), which means that when you edit the code, the browser page will be updated in real time without refreshing.

Build a production version

When you are ready to deploy the application, run the following command to build the production version:

npm run build
# Or use yarn
yarn build
Enter fullscreen mode Exit fullscreen mode

This will generate an optimized, production-ready static folder, usually located in the dist directory.

Vite configuration

// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'; // Assume we use Vue
import { resolve } from 'path';

// Environment variables
const env = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';

export default defineConfig({
// Application base path
base: '/my-app/',

// Project entry file
root: './src',

// Output directory
outDir: 'dist',

mode: env,
envPrefix: 'VITE_', // All environment variables starting with VITE_ will be injected into import.meta.env
envFile: `.env.${env}.local`, // Read the .env file for the corresponding environment

// Dynamically import polyfill
optimizeDeps: {
    include: ['@vue/reactivity'], // Force inclusion of dynamically imported libraries
},

// Server configuration
server: {
    // Server port
    port: 3000,
    // Whether to enable HTTPS
    https: false,
    // Enable hot module replacement
    hmr: true,
    // Proxy configuration for API request forwarding
    proxy: {
        '/api': {
            target: 'http://localhost:8000',
            changeOrigin: true,
        },
    },
    middlewareMode: true, // Enable middleware mode
    before(app) {
        app.use(async (ctx, next) => {
            ctx.body = 'Hello, this is a custom middleware!';
            await next();
        });
    },
},

// Build configuration
build: {
    // Whether to compress code in the production environment
    minify: true,
    // Output directory
    outDir: 'dist',
    // Resource file storage directory
    assetsDir: 'assets',
    // Chunk size warning threshold
    chunkSizeWarningLimit: 500,
    rollupOptions: {
        input: 'src/main.js',
        output: {
            manualChunks(id) {
                if (id.startsWith('node_modules')) {
                    return id.toString().replace(/(\.[a-z]+)|[\\/]/g, '_');
                }
            },
        },
    },
},

// Preprocessor configuration, such as CSS
css: {
    // CSS modularization
    modules: {
        generateScopedName: '[name]_[local]_[hash:base64:5]',
    },
},

// Preview environment configuration
preview: {
    port: 8080,
},

// Plugin configuration
plugins: [
// You can add custom or third-party plugins here
],

// Resolve options
resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    // Alias ​​configuration
    alias: {
        '@': '/src',
    },
},

// Esbuild configuration for optimizing build speed
esbuild: {
    // Enable/disable esbuild tree shaking
    treeShaking: true,
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
},

transpileDependencies: ['my-dep'], // Specify dependencies to be translated

// Additional Rollup configuration
rollupOptions: {
// You can add Rollup configuration items here
},
});
Enter fullscreen mode Exit fullscreen mode

Vite's core features

  • Quick Start: Vite leverages the browser's native ES module support to quickly start the development server without bundling, significantly improving the startup speed.
  • Compile on demand: In development mode, Vite only compiles the module you are viewing, greatly speeding up the edit-refresh cycle.
  • Hot Module Replacement (HMR): Vite provides a very fast HMR experience, almost seamless real-time updates.
  • Simple configuration: Vite's configuration file vite.config.js is more concise than Webpack, lowering the entry threshold.
  • Good compatibility: Vite supports a variety of frameworks, including Vue, React, Preact, Svelte, etc., and can easily adapt to custom configurations.
  • Plugin system: Vite provides a powerful plugin system that allows developers to extend its functionality to meet specific project needs.

Advanced Exploration

  • Configuration file: Although Vite's default configuration is already powerful, you can make more customizations in vite.config.js, such as configuring proxies, aliases, CSS preprocessors, etc.
  • Vue DevTools: When developing Vue applications, make sure to install and enable the Vue DevTools browser extension for better debugging of application status.
  • TypeScript support: If you use TypeScript in your project, Vite already supports it by default. You only need to include .ts or .tsx files in your project.
  • Optimization: Learn how to use Vite's built-in optimization options and external plugins to further improve application performance.

Top comments (0)