Skip to content
文章摘要

了解unplugin体系,以及简单使用

unplugin 是一个为 Vite、Rollup、Webpack 等构建工具开发的统一插件系统,nice。可以直接生成针对多个平台的插件系统,可谓是一劳永逸。

基本使用

ts
import { createUnplugin } from 'unplugin'
export const unplugin = createUnplugin((options: UserOptions) => {
  return {
    name: 'unplugin-prefixed-name',
    // webpack's id filter is outside of loader logic,
    // an additional hook is needed for better perf on webpack
    transformInclude (id) {
      return id.endsWith('.vue')
    },
    // just like rollup transform
    transform (code) {
      return code.replace(/<template>/, `<template><div>Injected</div>`)
    },
    // more hooks coming
  }
})

export const vitePlugin = unplugin.vite
export const rollupPlugin = unplugin.rollup
export const webpackPlugin = unplugin.webpack
export const esbuildPlugin = unplugin.esbuild

原文:unplugin extends the excellent Rollup plugin API as the unified plugin interface and provides a compatible layer base on the build tools used with.

翻译:unplugin扩展了出色的Rollup插件API作为统一的插件接口,并提供了一个兼容的构建工具层。

所以说是在Rollup插件API基础上进行的兼容,所以如果了解Rollup插件的话对于unplugin更加得心应手。

可以先来看看 Rollup 官方文档上的流程图,加深印象。

name

插件名称,不过使用 unplugin 开发的插件,建议添加unplugin-前缀,以及package.json添加unplugin关键词。

enforce

插件执行顺序

"pre" | "post" | null

buildStart

构建开始

resolveId

loadInclude

transformInclude

transform

转换

ts
/**
 * code 代码内容
 * id 文件地址
 */
transform (code,id) {
    return code.replace(/<template>/, `<template><div>Injected</div>`)
},

buildEnd

构建结束