Glittering's blog Glittering's blog
Home
  • 学习手册

    • 《JavaScript教程》
    • 《ES6 教程》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • 《Vite》
    • 《Vue3》
    • TypeScript
    • CSS
  • 技术文档
  • 算法
  • 工作总结
  • 实用技巧
  • collect
About
  • Classification
  • Label
GitHub (opens new window)

Glitz Ma

前端开发工程师
Home
  • 学习手册

    • 《JavaScript教程》
    • 《ES6 教程》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • 《Vite》
    • 《Vue3》
    • TypeScript
    • CSS
  • 技术文档
  • 算法
  • 工作总结
  • 实用技巧
  • collect
About
  • Classification
  • Label
GitHub (opens new window)
  • vite从入门到精通
  • vite插件
    • 🚀 目标:写一个真正能运行的 Vite 插件
      • 功能:自动将代码中的 `console.log` 编译时移除
    • 📌 Step 1:插件的基础结构
    • 📌 Step 2:理解插件生命周期
    • 📌 Step 3:实现 transform() 处理代码
    • ✔ 实现插件功能(初版)
    • 📌 Step 4:在 Vite 中使用插件
    • 📢 你现在已经会写一个基础 Vite 插件了
    • ⭐ Step 5:支持多种 console 方法(更专业)
    • ⭐ Step 6:只在生产环境移除 console
    • ⭐ Step 7:支持用户自定义配置(专业插件必备)
    • ⭐ Step 8:支持 sourcemap(进阶)
    • ⭐ Step 9:支持 HMR(选学)
    • 🧱 一个完整、专业、可发布的插件结构
  • vite自动导入api插件
  • Vite 开发服务器核心原理讲解
  • Vite HMR源码级讲解
  • Vite虚拟模块插件
  • 模拟 Vite 内置env
  • vite一体化虚拟模块插件
  • vite可发布npm的虚拟插件
  • 《Vite》学习笔记
mamingjuan
2024-07-20
目录

vite插件

从 0 写一个 Vite 插件的最完整、最系统、最清晰的步骤教程。 你看完之后,不但能写插件,还能理解整个 Vite 插件体系的运行机制。


# 🚀 目标:写一个真正能运行的 Vite 插件

我们将从零构建一个插件:

# 功能:自动将代码中的 console.log 编译时移除

例如:

console.log("hello")
1

构建后变成:

// 被移除
1

你将学会:

  • 插件结构
  • Vite 插件生命周期
  • transform 钩子
  • 处理文件 ID
  • 热更新行为

然后再逐步升级插件。


# 📌 Step 1:插件的基础结构

一个 Vite 插件本质上就是一个 函数返回一个对象:

export default function myPlugin() {
  return {
    name: 'my-plugin',
  }
}
1
2
3
4
5

这是 Vite 最基本的插件结构。


# 📌 Step 2:理解插件生命周期

Vite 插件 API = Rollup 插件 + Vite 自己扩展。

你最常用的是这些 hook:

hook 作用
config 修改 Vite 配置
configureServer dev server 中间件
resolveId 路径解析
load 自定义内容返回
transform 修改源码的核心 hook
handleHotUpdate HMR

我们现在只需要 transform。


# 📌 Step 3:实现 transform() 处理代码

我们的目标:删掉 console.log(...)。

transform hook 会接受两个参数:

transform(code, id) { ... }
1
  • code:当前文件的源码
  • id:包括路径、query、样式后缀等,例如:
/src/main.js?import
1

# ✔ 实现插件功能(初版)

在项目根创建 plugins/remove-console.js:

export default function removeConsole() {
  return {
    name: 'vite-plugin-remove-console',

    transform(code, id) {
      if (!id.endsWith('.js') && !id.endsWith('.ts')) return;

      // 简单替换逻辑
      const transformed = code.replace(/console\.log\(.*?\);?/g, '')

      return {
        code: transformed,
        map: null, // 可选:不生成 sourcemap
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 📌 Step 4:在 Vite 中使用插件

vite.config.js:

import removeConsole from './plugins/remove-console.js'

export default {
  plugins: [
    removeConsole()
  ]
}
1
2
3
4
5
6
7

启动项目:

npm run dev
1

打开控制台,你会看到所有 console.log 在编译阶段已被移除。


# 📢 你现在已经会写一个基础 Vite 插件了

下面我们继续升级,让你进入真正的“插件开发者”层级。


# ⭐ Step 5:支持多种 console 方法(更专业)

比如:

  • console.info
  • console.debug
  • console.warn
  • console.error(可选)

使用正则:

const regex = /console\.(log|info|debug)\(.*?\);?/g
1

修改插件:

const transformed = code.replace(
  /console\.(log|info|debug)\(.*?\);?/g,
  ''
)
1
2
3
4

# ⭐ Step 6:只在生产环境移除 console

export default function removeConsole() {
  return {
    name: 'vite-plugin-remove-console',

    apply: 'build', // 仅在 build 阶段启用

    transform(code, id) {
      if (!id.match(/\.(js|ts)$/)) return

      return code.replace(
        /console\.(log|info|debug)\(.*?\);?/g,
        ''
      )
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# ⭐ Step 7:支持用户自定义配置(专业插件必备)

让插件更灵活:

export default function removeConsole(options = {}) {
  const methods = options.methods || ['log', 'info', 'debug']

  const reg = new RegExp(`console\\.(${methods.join('|')})\\(.*?\\);?`, 'g')

  return {
    name: 'vite-plugin-remove-console',

    apply: 'build',

    transform(code, id) {
      if (!id.match(/\.(js|ts)$/)) return
      return code.replace(reg, '')
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

用户这样用:

removeConsole({
  methods: ['log', 'debug']
})
1
2
3

# ⭐ Step 8:支持 sourcemap(进阶)

返回:

return {
  code: transformed,
  map: this.getCombinedSourcemap()
}
1
2
3
4

# ⭐ Step 9:支持 HMR(选学)

如果你要在 dev 模式也移除 console,HMR 要保持一致。

handleHotUpdate(ctx) {
  console.log('File changed:', ctx.file)
}
1
2
3

# 🧱 一个完整、专业、可发布的插件结构

完整插件文件(完整版):

vite-plugin-remove-console/
 ├─ index.js
 ├─ package.json
 ├─ README.md
 └─ LICENSE
1
2
3
4
5

index.js:

export default function removeConsole(options = {}) {
  const methods = options.methods || ['log', 'info', 'debug']

  const reg = new RegExp(
    `console\\.(${methods.join('|')})\\(.*?\\);?`,
    'g'
  )

  return {
    name: 'vite-plugin-remove-console',
    apply: options.apply || 'build',

    transform(code, id) {
      if (!id.match(/\.(js|ts)$/)) return

      const transformed = code.replace(reg, '')

      return {
        code: transformed,
        map: null,
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

上次更新: 2025/12/09, 03:15:37
vite从入门到精通
vite自动导入api插件

← vite从入门到精通 vite自动导入api插件→

Copyright © 2015-2025 Glitz Ma
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式