了解 Vite 插件

本文详细介绍了Vite插件如何优化项目构建,如vite-plugin-eslint的代码分析功能。展示了不同类型的Vite插件钩子(如config、configureServer等),强调了Vite插件系统在提升开发效率和扩展性上的作用。
摘要由CSDN通过智能技术生成

众所周知 Vite 是基于 Rollup 的构建工具,Vite 插件为了优化、扩展项目构建系统功能的工具。

比如 vite-plugin-eslint 为我们提供了代码分析的功能,帮助我们在开发过程中的风格一致性。

简单示例

本文中的示例是基于 Vite + Vue3.x + TypeScript 来实现。

插件命名应该遵守社区的规则,如果你的插件不使用 Vite 特有的钩子,应该使用 rollup-plugin- 作为前缀;反之应该使用 vite-plugin- 作文前缀,如果插件只适用于特定的框架,应该使用 vite-plugin-vue- 作为前缀。

// plugins/vite-plugin-xxx/index.ts
import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
  }
}

apply 默认在开发 serve 和构建 build 模式下都会调用。

钩子函数

Vite 插件的钩子函数可以帮助我们在构建流程中插入自定义的事件逻辑;

由于 Vite 是基于 Rollup 实现的,所有 Vite 在遵循 Rollup 构建时的钩子同时为我们提供了 Vite 独有的钩子。

config

config 钩子在运行前执行,用于解析与修改 Vite 的默认配置。

import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
    config(config, { command }) {
      if (command === 'serve') {
        config.server.port = 3000
      }
    },
  }
}

以上的示例中,我们对原有配置的默认端口号5173修改为3000,当然这样的修改毫无意义,因为我们可以在 vite.config.ts 中直接去修改端口号,而本篇文章的目的是为了理解 config 钩子的作用。

configResolved

configResolved 钩子在解析 Vite 配置之后调用,用于获取最终的配置。

在以下的示例中对参数的进行校验以及插件初始化任务的执行。

import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
    config(config) {
      console.log('config', config)
    },
    configResolved(resolvedConfig) {
      console.log('configResolved', resolvedConfig)

      // 判断参数是否正确
      if (!resolvedConfig.base) {
        console.error('配置错误')
        return
      }

      // 初始化任务
      // initCoustomPlugin(resolvedConfig)
    },
  }
}

configureServer

configureServer 钩子用于配置开发服务器的钩子,我们通常在这里添加自定义的中间件。

在以下的示例中自定义了一个 /_dev 的接口,由此可见通过 configureServer 钩子可以在开发阶段与项目进行结合,可以扩展前端操作 os 等能力。

import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
    configureServer(server) {
      server.middlewares.use('/_dev', async (req, res) => {
        res.writeHead(200, { 'Content-Type': 'application/json' })
        res.end('Hello VitePlugin')
      })
    },
  }
}

configurePreviewServer

configurePreviewServer 钩子与 configureServer 钩子一样,但 configurePreviewServer 用于预览服务器,通过 vite preview 命令启动。

import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
    configurePreviewServer(server) {
      server.middlewares.use('/_dev', async (req, res) => {
        res.writeHead(200, { 'Content-Type': 'application/json' })
        res.end('Hello PreviewServer')
      })
    },
  }
}

transformIndexHtml

transformIndexHtml 钩子可以动态的修改或者注入 HTML 的内容,以及实现自定义的处理逻辑。

比如一下的示例中,我们在 #app 的节点下插入了 loading... 的文案,由此我们可以扩展更多的玩法,比如注入一些 loading 加载的动画。

import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
    transformIndexHtml(html) {
      return html.replace('<div id="app">', `<div id="app">loading...`)
    },
  }
}

handleHotUpdate

handleHotUpdate 钩子用于自定义执行 HMR 热更新的处理。

import type { Plugin } from 'vite'

export default (): Plugin => {
  return {
    name: 'vite-plugin-xxx',
    apply: 'serve',
    handleHotUpdate(ctx) {
      // 热更新的文件信息
      console.log(ctx)

      // 热更新自定义事件
      ctx.server.ws.send({
        type: 'custom',
        event: 'custom',
        data: 'custom',
      })
    },
  }
}

页面上调用监听,并自定义处理更新的逻辑。

if (import.meta.hot) {
  import.meta.hot.on('custom', data => {
    // 执行自定义更新
    console.log(data)
  })
}

总结

Vite 插件系统为开发者提供了丰富的扩展,极大提高了开发的效率以及项目构建时的扩展性。

在日常开发过程中,使用 Vite 的插件,编写自己的插件,通过 Vite 插件的系统简化工作的流程是非常棒的一件事情。

最后

感谢你的阅读~

如果你有任何的疑问欢迎您在后台私信,我们一同探讨学习!

如果觉得这篇文章对你有所帮助,点赞、在看是最大的支持!

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要了解 Vite 的基本用法和插件开发的规范。 Vite 是一个基于 ES Modules 的快速开发工具,它支持开发 JavaScript、TypeScript、CSS 等前端应用和插件。在 Vite 中,插件是通过导入一个函数并在配置文件中调用来注册的。 下面是一个最简单的 Vite 插件示例: ```js // plugin.js export default function myPlugin() { return { name: 'my-plugin', configureWebpack(config) { // 修改 Webpack 配置 } } } ``` 在这个示例中,我们定义了一个名为 `myPlugin` 的函数,并返回一个对象,其中包含一个名为 `name` 的属性和一个名为 `configureWebpack` 的函数。`name` 属性是必需的,因为它用于在 Vite 的日志中标识插件。`configureWebpack` 函数则允许我们修改 Webpack 配置。 接下来,我们需要在 Vite 的配置文件中导入并调用我们的插件函数: ```js // vite.config.js import myPlugin from './plugin.js' export default { plugins: [ myPlugin() ] } ``` 这样,我们就完成了一个最简单的 Vite 插件。你可以在 `configureWebpack` 函数中添加任何你需要的 Webpack 配置选项,或者在插件函数中实现其他功能。 具体开发过程中,你需要考虑你的插件的实际需求,然后在插件函数中实现相应的逻辑。例如,如果你需要在 Vite 中添加一个自定义的命令行选项,可以使用 `createServer` 函数和 `configureServer` 函数来实现。如果你需要修改 Vite 的构建流程,可以使用 `configureBuild` 函数来实现。 总之,插件开发是一个相对灵活和自由的过程,你可以根据自己的需求来实现任何你想要的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值