Skip to content
/ BundleTools/Vite
9/17/2024
1.6m
AI 摘要

本文介绍了 Vite 作为前端构建工具的优势,如支持 .vue 文件、自定义插件配置、生成浏览器兼容的 umd 包等。重点讲解了 transform 插件 API 的使用,以及 enforce 参数对插件执行顺序的影响。

Vite

Vite is still my favorite bundling tool. The out-of-box features, save a lot of time for developer.

There are some situation where I would choose vite:

  • For front-end project, such as involving .vue files.
  • Require some custom plugin configurations, and don't want configure from scratch.
  • The outputs are browser-friendly, for example, support umd bundling.
  • Starting a server easily.

With esbuild

Vite use esbuild to transform files

Plugin API

transform

This is a very commonly used hook for transforming the contents of files.

import { Plugin } from 'vite'
export default function myPlugin(): Plugin {
    return {
        name: 'transform-file',
        /**
         * @params code - code for each file
         * @params id - absolute path
         */
        transform(code, id) {
            // ...
        },
    }
}

We can transform source code in this plugin. Give two examples:

  1. unplugin/unplugin-auto-import: Auto-completion of missing imports in files:
  1. timyourivh/vite-plugin-json5: transform the json5 that can't be resolved in javascript:

enforce

The enforce control when the plugin is executed

import { Plugin } from 'vite'
export default function myPlugin(): Plugin {
    return {
        name: 'transform-file',
        enforce: 'pre', // default: 'post'
        transform(code, id, options) {
            // when enforce is pre, the TS syntax will be preserved in code
            // when enforce is post,it will be removed by vite's built-in plugins.
        },
    }
}

Released under the MIT License.