美文网首页
[vite源码解析]插件篇

[vite源码解析]插件篇

作者: 秋名山车神12138 | 来源:发表于2021-07-10 09:02 被阅读0次

vite的插件基于rollup,在本地服务生成是会同事创建插件容器,按顺序针对插件中的hook做批量调用,当前支持的hook有(区分构建和开发):

  • 通用hook
    |hook名称|触发时机|
    |---|---|
    |options|服务器启动时被调用|
    |buildStart|服务器启动时被调用|
    |resolveId|每个传入模块请求时被调用|
    |load|每个传入模块请求时被调用|
    |transform|每个传入模块请求时被调用|
    |buildEnd|服务器关闭时被调用|
    |closeBundle|服务器关闭时被调用|

  • vite独有hook

下一个问题,vite是如何实现插件的设计的?答案我们从createPluginContainer里面找

// packages/vite/src/node/server/pluginContainer.ts

export async function createPluginContainer(
  { plugins, logger, root, build: { rollupOptions } }: ResolvedConfig,
  watcher?: FSWatcher
): Promise<PluginContainer>

createPluginContainer传入2个参数:

  • resolveConfig配置:包含了plugins,logger, root, build(包含rollupOptions),这里实际对应的就是创建server的config,只不过用resolveConfig函数解析了下。
  • watcher:文件监控器,在创建server的时候调用的是chokidar实例来实现

返回的就是PluginContainer。
函数体其中也包含很多内容

function warnIncompatibleMethod(method: string, plugin: string){}
// 针对每个异步pipeline都创建一个上下文来跟踪多pipeline下追踪到当前激活的插件
class Context implements PluginContext {}

function formatError(){}

class TransformContext extends Context 

const container: PluginContainer 

return container

在这里我们看到上面的主要container就是pluginContainer,我们具体来看看里面包含哪些内容:

const container: PluginContainer = {
  options: await (async ()=>{})(),
  async buildStart(){}
async resolveId(rawId, importer = join(root, 'index.html'), skips, ssr){}
async load(id, ssr){}
async transform(code, id, inMap, ssr){}
watchChange(id, event = 'update'){}
async close(){}
}

可以看到插件容器主要就是包含选项的初始化,rollup 各个特定hook的调用(buildStart,resolveId,load,transform),变化监控同步函数watchChange,以及最后的close方法。下面我们来逐个拆解:

  • options异步函数解析:
  1. 将每个插件里的options方法执行了一遍
    for (const plugin of plugins) {
        if (!plugin.options) continue
        options =
          (await plugin.options.call(minimalContext, options)) || options
      }
  1. 如果有配置acornInjectPlugins:那就合并进acore的parser中:
if (options.acornInjectPlugins) {
        parser = acorn.Parser.extend(
          ...[
            acornClassFields,
            acornStaticClassFeatures,
            acornNumericSeparator
          ].concat(options.acornInjectPlugins)
        )
      }
  1. 返回包含acorn及options的对象
return {
        acorn,
        acornInjectPlugins: [],
        ...options
      }

  • buildStart: 使用promise.all把所有插件里面但凡有该配置的都执行下
await Promise.all(
        plugins.map((plugin) => {
          if (plugin.buildStart) {
            return plugin.buildStart.call(
              new Context(plugin) as any,
              container.options as NormalizedInputOptions
            )
          }
        })
      )

  • resolveId:resolveId阶段属于rollup的通用hook,流程也类似,针对每个plugin执行对应钩子:
for (const plugin of plugins) {
 // 没有就跳过
        if (!plugin.resolveId) continue
// 如果在跳过的列表里面,也跳过
        if (skips?.has(plugin)) continue
// 将该插件设置为当前激活插件
        ctx._activePlugin = plugin
// 开始调用方法
        const result = await plugin.resolveId.call(
          ctx as any,
          rawId,
          importer,
          {},
          ssr
        )
// 如果没结果就跳过到下一个
        if (!result) continue
// 如果结果为string,那结果就是对应的id
        if (typeof result === 'string') {
           id = result
        } else {
// 如果不是那就是object对象,找到对应id属性
          id = result.id
          Object.assign(partial, result)
        }

        // resolveId() is hookFirst - first non-null result is returned.
        break
      }
// 如果id有了,就返回partial,没有返回null
if (id) {
        partial.id = isExternalUrl(id) ? id : normalizePath(id)
        return partial as PartialResolvedId
      } else {
        return null
      }

  • load阶段:遍历plugin执行hook, 有结果就返回,没有返回null
for (const plugin of plugins) {
        if (!plugin.load) continue
        ctx._activePlugin = plugin
        const result = await plugin.load.call(ctx as any, id, ssr)
        if (result != null) {
          return result
        }
      }
      return null

  • transform阶段:遍历plugin执行hook, 有结果就返回,没有返回null
for (const plugin of plugins) {
        if (!plugin.transform) continue
        ctx._activePlugin = plugin
        ctx._activeId = id
        ctx._activeCode = code
        let result
        try {
          result = await plugin.transform.call(ctx as any, code, id, ssr)
        } catch (e) {
          ctx.error(e)
        }
        if (!result) continue
     
        if (typeof result === 'object') {
          code = result.code || ''
          if (result.map) ctx.sourcemapChain.push(result.map)
        } else {
          code = result
        }
      }
// 返回code及对应的sourcemap
      return {
        code,
        map: ctx._getCombinedSourcemap()
      }

  • watchChange:遍历plugin执行hook
for (const plugin of plugins) {
  if (!plugin.watchChange) continue
      ctx._activePlugin = plugin
      plugin.watchChange.call(ctx as any, id, { event })
 }

  • close: 按照先后顺序执行buildEnd ,closeBundle hook, 配置close状态位
if (closed) return
      const ctx = new Context()
      await Promise.all(
        plugins.map((p) => p.buildEnd && p.buildEnd.call(ctx as any))
      )
      await Promise.all(
        plugins.map((p) => p.closeBundle && p.closeBundle.call(ctx as any))
      )
      closed = true
 }

总结

插件容器针对插件提供了统一的管理和调用方案,在每个阶段调用并传递对应上下文。

相关文章

  • [vite源码解析]插件篇

    vite的插件基于rollup,在本地服务生成是会同事创建插件容器,按顺序针对插件中的hook做批量调用,当前支持...

  • [vite源码解析]cli篇

    首先我们来看入口文件:/vite/packages/vite/bin/vite.js 第1步: 判断当前目录是否包...

  • [vite源码解析]server篇

    我们从上一篇的cli[https://www.jianshu.com/p/c15fe78bece8]可以看到cli...

  • [vite源码解析]client篇

    从服务端我们了解到是接住websocket与客户端进行通信,下面我们来看一下客户端的代码: 第1步 初始化webs...

  • [vite源码解析] 总览

    Vite (法语意为 "快速的",发音 /vit/) 是一种新型前端构建工具,能够显著提升前端开发>体验。它主要由...

  • 插件化学习

    atlas学习传送门github demo地址atlas插件化源码解析atlas插件化官方文档atlas原理细节解析

  • Android插件化热修复

    项目实战之插件化VirtualAPK 使用滴滴插件化方案 VirtualApk 源码解析VirtualAPK 踩坑...

  • vite-ts-vue3.0引入svg

    使用vite-plugin-svg-icons插件 vite.config.ts 中的配置插件 在 src/mai...

  • 构建一个 Vite + Vue3 项目 开发Cesium

    搭建第一个 Vite 项目 yarn 安装 cesium 安装 vite 插件 配置 vite.config.js...

  • webpack 源码解析1

    源码解析1 打包文件解析 安装 webpack 插件 新建 src/index.js data.js,写点写点内容...

网友评论

      本文标题:[vite源码解析]插件篇

      本文链接:https://www.haomeiwen.com/subject/futcpltx.html