从零到一解读Rollup Plugin

开发 前端
rollup 的插件本质是一个处理函数,返回一个对象。返回的对象包含一些属性(如 name),和不同阶段的钩子函数(构建 build 和输出 output 阶段),以实现插件内部的功能.

[[431668]]

rollup plugin 这篇文章读读改改,终于和大家见面啦~~~

尽管对于 rollup 的插件编写,官网上对于 rolup 插件的介绍几乎都是英文,学习起来不是很友好, 例子也相对较少,但目前针对 rollup 插件的分析与开发指南的文章已经不少见,以关于官方英文文档的翻译与函数钩子的分析为主。

讲道理,稀里糊涂直接看源码分析只会分分钟劝退我,而我只想分分钟写个 rollup 插件而已~~

rollup 为什么需要 Plugin

rollup -c 打包流程

在 rollup 的打包流程中,通过相对路径,将一个入口文件和一个模块创建成了一个简单的 bundle。随着构建更复杂的 bundle,通常需要更大的灵活性——引入 npm 安装的模块、通过 Babel 编译代码、和 JSON 文件打交道等。通过 rollup -c 打包的实现流程可以参考下面的流程图理解。

为此,我们可以通过 插件(plugins) 在打包的关键过程中更改 Rollup 的行为。

这其实和 webpack 的插件相类似,不同的是,webpack 区分 loader 和 plugin,而 rollup 的 plugin 既可以担任 loader 的角色,也可以胜任传统 plugin 的角色。

理解 rollup plugin

引用官网的解释:Rollup 插件是一个具有下面描述的一个或多个属性、构建钩子和输出生成钩子的对象,它遵循我们的约定。一个插件应该作为一个包来分发,该包导出一个可以用插件特定选项调用的函数,并返回这样一个对象。插件允许你定制 Rollup 的行为,例如,在捆绑之前编译代码,或者在你的 node_modules 文件夹中找到第三方模块。

简单来说,rollup 的插件是一个普通的函数,函数返回一个对象,该对象包含一些属性(如 name),和不同阶段的钩子函数(构建 build 和输出 output 阶段),此处应该回顾下上面的流程图。

关于约定

  • 插件应该有一个带有 rollup-plugin-前缀的明确名称。
  • 在 package.json 中包含 rollup-plugin 关键字。
  • 插件应该支持测试,推荐 mocha 或者 ava 这类开箱支持 promises 的库。
  • 尽可能使用异步方法。
  • 用英语记录你的插件。
  • 确保你的插件输出正确的 sourcemap。
  • 如果你的插件使用 'virtual modules'(比如帮助函数),给模块名加上 \0 前缀。这可以阻止其他插件执行它。

分分钟写个 rollup 插件

为了保持学习下去的热情与动力,先举个栗子压压惊,如果看到插件实现的各种源码函数钩子部分觉得脑子不清醒了,欢迎随时回来重新看这一小节,重拾勇气与信心!

插件其实很简单

可以打开rollup 插件列表,随便找个你感兴趣的插件,看下源代码。

有不少插件都是几十行,不超过 100 行的。比如图片文件多格式支持插件@rollup/plugin-image 的代码甚至不超过 50 行,而将 json 文件转换为 ES6 模块的插件@rollup/plugin-json 源代码更少。

一个例子

  1. // 官网的一个例子 
  2. export default function myExample () { 
  3.   return { 
  4.     name'my-example', // 名字用来展示在警告和报错中 
  5.     resolveId ( source ) { 
  6.       if (source === 'virtual-module') { 
  7.         return source; // rollup 不应该查询其他插件或文件系统 
  8.       } 
  9.       return null; // other ids 正常处理 
  10.     }, 
  11.     load ( id ) { 
  12.       if (id === 'virtual-module') { 
  13.         return 'export default "This is virtual!"'; // source code for "virtual-module" 
  14.       } 
  15.       return null; // other ids 
  16.     } 
  17.   }; 
  18.  
  19. // rollup.config.js 
  20. import myExample from './rollup-plugin-my-example.js'
  21. export default ({ 
  22.   input: 'virtual-module', // 配置 virtual-module 作为入口文件满足条件通过上述插件处理 
  23.   plugins: [myExample()], 
  24.   output: [{ 
  25.     file: 'bundle.js'
  26.     format: 'es' 
  27.   }] 
  28. }); 

光看不练假把式,模仿写一个:

  1. // 自己编的一个例子 QAQ 
  2. export default function bundleReplace () { 
  3.   return { 
  4.     name'bundle-replace', // 名字用来展示在警告和报错中 
  5.     transformBundle(bundle) { 
  6.       return bundle 
  7.         .replace('key_word''replace_word'
  8.         .replace(/正则/, '替换内容'); 
  9.     }, 
  10.   }; 
  11.  
  12. // rollup.config.js 
  13. import bundleReplace from './rollup-plugin-bundle-replace.js'
  14. export default ({ 
  15.   input: 'src/main.js', // 通用入口文件 
  16.   plugins: [bundleReplace()], 
  17.   output: [{ 
  18.     file: 'bundle.js'
  19.     format: 'es' 
  20.   }] 
  21. }); 

嘿!这也不难嘛~~~

rollup plugin 功能的实现

我们要讲的 rollup plugin 也不可能就这么简单啦~~~

接下来当然是结合例子分析实现原理~~

其实不难发现,rollup 的插件配置与 webpack 等框架中的插件使用大同小异,都是提供配置选项,注入当前构建结果相关的属性与方法,供开发者进行增删改查操作。

那么插件写好了,rollup 是如何在打包过程中调用它并实现它的功能的呢?

相关概念

首先还是要了解必备的前置知识,大致浏览下 rollup 中处理 plugin 的方法,基本可以定位到 PluginContext.ts(上下文相关)、PluginDriver.ts(驱动相关)、PluginCache.ts(缓存相关)和 PluginUtils.ts(警告错误异常处理)等文件,其中最关键的就在 PluginDriver.ts 中了。

首先要清楚插件驱动的概念,它是实现插件提供功能的的核心 -- PluginDriver,插件驱动器,调用插件和提供插件环境上下文等。

钩子函数的调用时机

大家在研究 rollup 插件的时候,最关注的莫过于钩子函数部分了,钩子函数的调用时机有三类:

  • const chunks = rollup.rollup 执行期间的构建钩子函数 - Build Hooks
  • chunks.generator(write)执行期间的输出钩子函数 - Output Generation Hooks
  • 监听文件变化并重新执行构建的 rollup.watch 执行期间的 watchChange 钩子函数

钩子函数处理方式分类

除了以调用时机来划分钩子函数以外,我们还可以以钩子函数处理方式来划分,这样来看钩子函数就主要有以下四种版本:

  • async: 处理 promise 的异步钩子,即这类 hook 可以返回一个解析为相同类型值的 promise,同步版本 hook 将被标记为 sync。
  • first: 如果多个插件实现了相同的钩子函数,那么会串式执行,从头到尾,但是,如果其中某个的返回值不是 null 也不是 undefined 的话,会直接终止掉后续插件。
  • sequential: 如果多个插件实现了相同的钩子函数,那么会串式执行,按照使用插件的顺序从头到尾执行,如果是异步的,会等待之前处理完毕,在执行下一个插件。
  • parallel: 同上,不过如果某个插件是异步的,其后的插件不会等待,而是并行执行,这个也就是我们在 rollup.rollup() 阶段看到的处理方式。

构建钩子函数

为了与构建过程交互,你的插件对象需要包含一些构建钩子函数。构建钩子是构建的各个阶段调用的函数。构建钩子函数可以影响构建执行方式、提供构建的信息或者在构建完成后修改构建。rollup 中有不同的构建钩子函数,在构建阶段执行时,它们被 [rollup.rollup(inputOptions)](https://github.com/rollup/rollup/blob/07b3a02069594147665daa95d3fa3e041a82b2d0/cli/run/build.ts#L34) 触发。

构建钩子函数主要关注在 Rollup 处理输入文件之前定位、提供和转换输入文件。构建阶段的第一个钩子是 options,最后一个钩子总是 buildEnd,除非有一个构建错误,在这种情况下 closeBundle 将在这之后被调用。

顺便提一下,在观察模式下,watchChange 钩子可以在任何时候被触发,以通知新的运行将在当前运行产生其输出后被触发。当 watcher 关闭时,closeWatcher 钩子函数将被触发。

输出钩子函数

输出生成钩子函数可以提供关于生成的包的信息并在构建完成后立马执行。它们和构建钩子函数拥有一样的工作原理和相同的类型,但是不同的是它们分别被 ·[bundle.generate(output)](https://github.com/rollup/rollup/blob/07b3a02069594147665daa95d3fa3e041a82b2d0/cli/run/build.ts#L44) 或 [bundle.write(outputOptions)](https://github.com/rollup/rollup/blob/07b3a02069594147665daa95d3fa3e041a82b2d0/cli/run/build.ts#L64) 调用。只使用输出生成钩子的插件也可以通过输出选项传入,因为只对某些输出运行。

输出生成阶段的第一个钩子函数是 outputOptions,如果输出通过 bundle.generate(...) 成功生成则第一个钩子函数是 generateBundle,如果输出通过 [bundle.write(...)](https://github.com/rollup/rollup/blob/07b3a02069594147665daa95d3fa3e041a82b2d0/src/watch/watch.ts#L200) 生成则最后一个钩子函数是 [writeBundle](https://github.com/rollup/rollup/blob/master/src/rollup/rollup.ts#L176),另外如果输出生成阶段发生了错误的话,最后一个钩子函数则是 renderError。

另外,closeBundle 可以作为最后一个钩子被调用,但用户有责任手动调用 bundle.close() 来触发它。CLI 将始终确保这种情况发生。

以上就是必须要知道的概念了,读到这里好像还是看不明白这些钩子函数到底是干啥的!那么接下来进入正题!

钩子函数加载实现

[PluginDriver](https://github.com/rollup/rollup/blob/07b3a02069594147665daa95d3fa3e041a82b2d0/src/utils/PluginDriver.ts#L124) 中有 9 个 hook 加载函数。主要是因为每种类别的 hook 都有同步和异步的版本。

接下来先康康 9 个 hook 加载函数及其应用场景(看完第一遍不知所以然,但是别人看了咱也得看,先看了再说,看不懂就多看几遍 QAQ~)

排名不分先后,仅参考它们在 PluginDriver.ts 中出现的顺序🌠。

1. hookFirst

加载 first 类型的钩子函数,场景有 resolveId、resolveAssetUrl 等,在实例化 Graph 的时候,初始化初始化 promise 和 this.plugins,并通过覆盖之前的 promise,实现串行执行钩子函数。当多个插件实现了相同的钩子函数时从头到尾串式执行,如果其中某个的返回值不是 null 也不是 undefined 的话,就会直接终止掉后续插件。

  1. function hookFirst<H extends keyof PluginHooks, R = ReturnType<PluginHooks[H]>>( 
  2.   hookName: H, 
  3.   args: Args<PluginHooks[H]>, 
  4.   replaceContext?: ReplaceContext | null
  5.   skip?: number | null 
  6. ): EnsurePromise<R> { 
  7.   // 初始化 promise 
  8.   let promise: Promise<any> = Promise.resolve(); 
  9.   // 实例化 Graph 的时候,初始化 this.plugins 
  10.   for (let i = 0; i < this.plugins.length; i++) { 
  11.     if (skip === i) continue
  12.     // 覆盖之前的 promise,即串行执行钩子函数 
  13.     promise = promise.then((result: any) => { 
  14.       // 返回非 null 或 undefined 的时候,停止运行,返回结果 
  15.       if (result != nullreturn result; 
  16.       // 执行钩子函数 
  17.       return this.runHook(hookName, args as any[], i, false, replaceContext); 
  18.     }); 
  19.   } 
  20.   // 返回 hook 过的 promise 
  21.   return promise; 

2. hookFirstSync

hookFirst 的同步版本,使用场景有 resolveFileUrl、resolveImportMeta 等。

  1. function hookFirstSync<H extends keyof PluginHooks, R = ReturnType<PluginHooks[H]>>( 
  2.   hookName: H, 
  3.   args: Args<PluginHooks[H]>, 
  4.   replaceContext?: ReplaceContext 
  5. ): R { 
  6.   for (let i = 0; i < this.plugins.length; i++) { 
  7.     // runHook 的同步版本 
  8.     const result = this.runHookSync(hookName, args, i, replaceContext); 
  9.     // 返回非 null 或 undefined 的时候,停止运行,返回结果 
  10.     if (result != nullreturn result as any
  11.   } 
  12.   // 否则返回 null 
  13.   return null as any

3. hookParallel

并行执行 hook,不会等待当前 hook 完成。也就是说如果某个插件是异步的,其后的插件不会等待,而是并行执行。使用场景 buildEnd、buildStart、moduleParsed 等。

  1. hookParallel<H extends AsyncPluginHooks & ParallelPluginHooks>( 
  2.   hookName: H, 
  3.   args: Parameters<PluginHooks[H]>, 
  4.   replaceContext?: ReplaceContext 
  5. ): Promise<void> { 
  6.   const promises: Promise<void>[] = []; 
  7.   for (const plugin of this.plugins) { 
  8.     const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext); 
  9.     if (!hookPromise) continue
  10.     promises.push(hookPromise); 
  11.   } 
  12.   return Promise.all(promises).then(() => {}); 

4.hookReduceArg0

对 arg 第一项进行 reduce 操作。使用场景: options、renderChunk 等。

  1. function hookReduceArg0<H extends keyof PluginHooks, V, R = ReturnType<PluginHooks[H]>>( 
  2.     hookName: H, 
  3.     [arg0, ...args]: any[], // 取出传入的数组的第一个参数,将剩余的置于一个数组中 
  4.     reduce: Reduce<V, R>, 
  5.     replaceContext?: ReplaceContext // 替换当前 plugin 调用时候的上下文环境 
  6. ) { 
  7.   let promise = Promise.resolve(arg0); // 默认返回 source.code 
  8.   for (let i = 0; i < this.plugins.length; i++) { 
  9.     // 第一个 promise 的时候只会接收到上面传递的 arg0 
  10.     // 之后每一次 promise 接受的都是上一个插件处理过后的 source.code 值 
  11.     promise = promise.then(arg0 => { 
  12.       const hookPromise = this.runHook(hookName, [arg0, ...args], i, false, replaceContext); 
  13.       // 如果没有返回 promise,那么直接返回 arg0 
  14.       if (!hookPromise) return arg0; 
  15.       // result 代表插件执行完成的返回值 
  16.       return hookPromise.then((result: any) => 
  17.         reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]) 
  18.       ); 
  19.     }); 
  20.   } 
  21.   return promise; 

5.hookReduceArg0Sync

hookReduceArg0 同步版本,使用场景 transform、generateBundle 等,不做赘述。

6. hookReduceValue

将返回值减少到类型 T,分别处理减少的值。允许钩子作为值。

  1. hookReduceValue<H extends PluginValueHooks, T>( 
  2.   hookName: H, 
  3.   initialValue: T | Promise<T>, 
  4.   args: Parameters<AddonHookFunction>, 
  5.   reduce: ( 
  6.    reduction: T, 
  7.    result: ResolveValue<ReturnType<AddonHookFunction>>, 
  8.    plugin: Plugin 
  9.   ) => T, 
  10.   replaceContext?: ReplaceContext 
  11.  ): Promise<T> { 
  12.   let promise = Promise.resolve(initialValue); 
  13.   for (const plugin of this.plugins) { 
  14.    promise = promise.then(value => { 
  15.     const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext); 
  16.     if (!hookPromise) return value; 
  17.     return hookPromise.then(result => 
  18.      reduce.call(this.pluginContexts.get(plugin), value, result, plugin) 
  19.     ); 
  20.    }); 
  21.   } 
  22.   return promise; 
  23.  } 

7. hookReduceValueSync

hookReduceValue 的同步版本。

8. hookSeq

加载 sequential 类型的钩子函数,和 hookFirst 的区别就是不能中断,使用场景有 onwrite、generateBundle 等。

  1. async function hookSeq<H extends keyof PluginHooks>( 
  2.   hookName: H, 
  3.   args: Args<PluginHooks[H]>, 
  4.   replaceContext?: ReplaceContext, 
  5.   // hookFirst 通过 skip 参数决定是否跳过某个钩子函数 
  6. ): Promise<void> { 
  7.   let promise: Promise<void> = Promise.resolve(); 
  8.   for (let i = 0; i < this.plugins.length; i++) 
  9.     promise = promise.then(() => 
  10.       this.runHook<void>(hookName, args as any[], i, false, replaceContext), 
  11.     ); 
  12.   return promise; 

9.hookSeqSync

hookSeq 同步版本,不需要构造 promise,而是直接使用 runHookSync 执行钩子函数。使用场景有 closeWatcher、watchChange 等。

  1. hookSeqSync<H extends SyncPluginHooks & SequentialPluginHooks>( 
  2.   hookName: H, 
  3.   args: Parameters<PluginHooks[H]>, 
  4.   replaceContext?: ReplaceContext 
  5. ): void { 
  6.   for (const plugin of this.plugins) { 
  7.     this.runHookSync(hookName, args, plugin, replaceContext); 
  8.   } 

通过观察上面几种钩子函数的调用方式,我们可以发现,其内部有一个调用钩子函数的方法: runHook(Sync)(当然也分同步和异步版本),该函数真正执行插件中提供的钩子函数。

也就是说,之前介绍了那么多的钩子函数,仅仅决定了我们插件的调用时机和调用方式(比如同步/异步),而真正调用并执行插件函数(前面提到插件本身是个「函数」)的钩子其实是 runHook 。

runHook(Sync)

真正执行插件的钩子函数,同步版本和异步版本的区别是有无 permitValues 许可标识允许返回值而不是只允许返回函数。

  1. function runHook<T>( 
  2.   hookName: string, 
  3.   args: any[], 
  4.   pluginIndex: number, 
  5.   permitValues: boolean, 
  6.   hookContext?: ReplaceContext | null
  7. ): Promise<T> { 
  8.   this.previousHooks.add(hookName); 
  9.   // 找到当前 plugin 
  10.   const plugin = this.plugins[pluginIndex]; 
  11.   // 找到当前执行的在 plugin 中定义的 hooks 钩子函数 
  12.   const hook = (plugin as any)[hookName]; 
  13.   if (!hook) return undefined as any
  14.  
  15.   // pluginContexts 在初始化 plugin 驱动器类的时候定义,是个数组,数组保存对应着每个插件的上下文环境 
  16.   let context = this.pluginContexts[pluginIndex]; 
  17.   // 用于区分对待不同钩子函数的插件上下文 
  18.   if (hookContext) { 
  19.     context = hookContext(context, plugin); 
  20.   } 
  21.   return Promise.resolve() 
  22.     .then(() => { 
  23.       // 允许返回值,而不是一个函数钩子,使用 hookReduceValue 或 hookReduceValueSync 加载。 
  24.       // 在 sync 同步版本钩子函数中,则没有 permitValues 许可标识允许返回值 
  25.       if (typeof hook !== 'function') { 
  26.         if (permitValues) return hook; 
  27.         return error({ 
  28.           code: 'INVALID_PLUGIN_HOOK'
  29.           message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`, 
  30.         }); 
  31.       } 
  32.       // 传入插件上下文和参数,返回插件执行结果 
  33.       return hook.apply(context, args); 
  34.     }) 
  35.     .catch(err => throwPluginError(err, plugin.name, { hook: hookName })); 

看完这些钩子函数介绍,我们清楚了插件的调用时机、调用方式以及执行输出钩子函数。但你以为这就结束了??当然没有结束我们还要把这些钩子再带回 rollup 打包流程康康一下调用时机和调用方式的实例~~

rollup.rollup()

又回到最初的起点~~~

前面提到过,构建钩子函数在 Rollup 处理输入文件之前定位、提供和转换输入文件。那么当然要先从输入开始看起咯~

build 阶段

处理 inputOptions

  1. // 从处理 inputOptions 开始,你的插件钩子函数已到达! 
  2. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions( 
  3.   rawInputOptions, 
  4.   watcher !== null 
  5. ); 

朋友们,把 async、first、sequential 和 parallel 以及 9 个钩子函数带上开搞!

  1. // 处理 inputOptions 的应用场景下调用了 options 钩子 
  2. function applyOptionHook(watchMode: boolean) { 
  3.  return async ( // 异步串行执行 
  4.   inputOptions: Promise<GenericConfigObject>, 
  5.   plugin: Plugin 
  6.  ): Promise<GenericConfigObject> => { 
  7.   if (plugin.options) { // plugin 配置存在 
  8.    return ( 
  9.     ((await plugin.options.call( 
  10.      { meta: { rollupVersion, watchMode } }, // 上下文 
  11.      await inputOptions 
  12.     )) as GenericConfigObject) || inputOptions 
  13.    ); 
  14.   } 
  15.  
  16.   return inputOptions; 
  17.  }; 

接着标准化插件

  1. // 标准化插件 
  2. function normalizePlugins(plugins: Plugin[], anonymousPrefix: string): void { 
  3.  for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) { 
  4.   const plugin = plugins[pluginIndex]; 
  5.   if (!plugin.name) { 
  6.    plugin.name = `${anonymousPrefix}${pluginIndex + 1}`; 
  7.   } 
  8.  } 

生成 graph 对象处理

重点来了!const graph = new Graph(inputOptions, watcher);里面就调用了我们上面介绍的一些关键钩子函数了~

  1. // 不止处理缓存 
  2. this.pluginCache = options.cache?.plugins || Object.create(null); 
  3.  
  4. // 还有 WatchChangeHook 钩子 
  5. if (watcher) { 
  6.   this.watchMode = true
  7.   const handleChange: WatchChangeHook = (...args) => this.pluginDriver.hookSeqSync('watchChange', args); // hookSeq 同步版本,watchChange 使用场景下 
  8.   const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []); // hookSeq 同步版本, closeWatcher 使用场景下 
  9.   watcher.on('change', handleChange); 
  10.   watcher.on('close', handleClose); 
  11.   watcher.once('restart', () => { 
  12.     watcher.removeListener('change', handleChange); 
  13.     watcher.removeListener('close', handleClose); 
  14.   }); 
  15.  
  16. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache); // 生成一个插件驱动对象 
  17. ... 
  18. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver); // 初始化模块加载对象 

到目前为止,处理inputOptions生成了graph对象,还记不记得!我们前面讲过_graph 包含入口以及各种依赖的相互关系,操作方法,缓存等,在实例内部实现 AST 转换,是 rollup 的核心。

我们还讲过!在解析入口文件路径阶段,为了从入口文件的绝对路径出发找到它的模块定义,并获取这个入口模块所有的依赖语句,我们要先通过 resolveId()方法解析文件地址,拿到文件绝对路径。这个过程就是通过在 ModuleLoader 中调用 resolveId 完成的。resolveId() 我们在 tree-shaking 时讲到基本构建流程时已经介绍过的,下面看调用了钩子函数的具体方法~

  1. export function resolveIdViaPlugins( 
  2.  source: string, 
  3.  importer: string | undefined, 
  4.  pluginDriver: PluginDriver, 
  5.  moduleLoaderResolveId: ( 
  6.   source: string, 
  7.   importer: string | undefined, 
  8.   customOptions: CustomPluginOptions | undefined, 
  9.   skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null 
  10.  ) => Promise<ResolvedId | null>, 
  11.  skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null
  12.  customOptions: CustomPluginOptions | undefined 
  13. ) { 
  14.  let skipped: Set<Plugin> | null = null
  15.  let replaceContext: ReplaceContext | null = null
  16.  if (skip) { 
  17.   skipped = new Set(); 
  18.   for (const skippedCall of skip) { 
  19.    if (source === skippedCall.source && importer === skippedCall.importer) { 
  20.     skipped.add(skippedCall.plugin); 
  21.    } 
  22.   } 
  23.   replaceContext = (pluginContext, plugin): PluginContext => ({ 
  24.    ...pluginContext, 
  25.    resolve: (source, importer, { custom, skipSelf } = BLANK) => { 
  26.     return moduleLoaderResolveId( 
  27.      source, 
  28.      importer, 
  29.      custom, 
  30.      skipSelf ? [...skip, { importer, plugin, source }] : skip 
  31.     ); 
  32.    } 
  33.   }); 
  34.  } 
  35.  return pluginDriver.hookFirst( // hookFirst 被调用,通过插件处理获取就绝对路径,first 类型,如果有插件返回了值,那么后续所有插件的 resolveId 都不会被执行。 
  36.   'resolveId'
  37.   [source, importer, { custom: customOptions }], 
  38.   replaceContext, 
  39.   skipped 
  40.  ); 

拿到resolveId hook处理过返回的绝对路径后,就要从入口文件的绝对路径出发找到它的模块定义,并获取这个入口模块所有的依赖语句并返回所有内容。在这里,我们收集配置并标准化、分析文件并编译源码生成 AST、生成模块并解析依赖,最后生成 chunks,总而言之就是读取并修改文件!要注意的是,每个文件只会被一个插件的load Hook处理,因为它是以hookFirst来执行的。另外,如果你没有返回值,rollup 会自动读取文件。接下来进入 fetchModule 阶段~

  1. const module: Module = new Module(...) 
  2. ... 
  3. await this.pluginDriver.hookParallel('moduleParsed', [module.info]); // 并行执行 hook,moduleParsed 场景 
  4. ... 
  5. await this.addModuleSource(id, importer, module); 
  6. ...// addModuleSource 
  7. source = (await this.pluginDriver.hookFirst('load', [id])) ?? (await readFile(id)); // 在 load 阶段对代码进行转换、生成等操作 
  8. ...// resolveDynamicImport 
  9. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [ 
  10.   specifier, 
  11.   importer 
  12. ]); 

bundle 处理代码

生成的 graph 对象准备进入 build 阶段~~build 开始与结束中的插件函数钩子

  1. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]); // 并行执行 hook,buildStart 场景 
  2. ... 
  3. await graph.build(); 
  4. ... 
  5. await graph.pluginDriver.hookParallel('buildEnd', []); // 并行执行 hook,buildEnd 场景 

如果在 buildStart 和 build 阶段出现异常,就会提前触发处理 closeBundle 的 hookParallel 钩子函数:

  1. await graph.pluginDriver.hookParallel('closeBundle', []); 

generate 阶段

outputOptions

在 handleGenerateWrite() 阶段,获取处理后的 outputOptions。

  1. outputPluginDriver.hookReduceArg0Sync( 
  2.   'outputOptions'
  3.   [rawOutputOptions.output || rawOutputOptions] as [OutputOptions], 
  4.   (outputOptions, result) => result || outputOptions, 
  5.     pluginContext => { 
  6.     const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook()); 
  7.     return { 
  8.       ...pluginContext, 
  9.       emitFile: emitError, 
  10.       setAssetSource: emitError 
  11.     }; 
  12.   } 

将处理后的 outputOptions 作为传参生成 bundle 对象:

  1. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph); 

生成代码

在 const generated = await bundle.generate(isWrite); bundle 生成代码阶段,

  1. ... // render 开始 
  2. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]); 
  3. ... // 该钩子函数执行过程中不能中断 
  4. await this.pluginDriver.hookSeq('generateBundle', [ 
  5.   this.outputOptions, 
  6.   outputBundle as OutputBundle, 
  7.   isWrite 
  8. ]); 

最后并行执行处理生成的代码~

  1. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]); 

小结

不难看出插件函数钩子贯穿了整个 rollup 的打包过程,并扮演了不同角色,支撑起了相应功能实现。我们目前做的就是梳理并理解这个过程,再回过头来看这张图,是不是就清晰多了。

最后再来讲讲 rollup 插件的两个周边叭~

插件上下文

rollup 给钩子函数注入了 context,也就是上下文环境,用来方便对 chunks 和其他构建信息进行增删改查。也就是说,在插件中,可以在各个 hook 中直接通过 this.xxx 来调用上面的方法。

  1. const context: PluginContext = { 
  2.     addWatchFile(id) {}, 
  3.     cache: cacheInstance, 
  4.     emitAsset: getDeprecatedContextHandler(...), 
  5.     emitChunk: getDeprecatedContextHandler(...), 
  6.     emitFile: fileEmitter.emitFile, 
  7.     error(err) 
  8.     getAssetFileName: getDeprecatedContextHandler(...), 
  9.     getChunkFileName: getDeprecatedContextHandler(), 
  10.     getFileName: fileEmitter.getFileName, 
  11.     getModuleIds: () => graph.modulesById.keys(), 
  12.     getModuleInfo: graph.getModuleInfo, 
  13.     getWatchFiles: () => Object.keys(graph.watchFiles), 
  14.     isExternal: getDeprecatedContextHandler(...), 
  15.     meta: { // 绑定 graph.watchMode 
  16.         rollupVersion, 
  17.         watchMode: graph.watchMode 
  18.     }, 
  19.     get moduleIds() { // 绑定 graph.modulesById.keys(); 
  20.         const moduleIds = graph.modulesById.keys(); 
  21.         return wrappedModuleIds(); 
  22.     }, 
  23.     parse: graph.contextParse, // 绑定 graph.contextParse 
  24.     resolve(source, importer, { custom, skipSelf } = BLANK) { // 绑定 graph.moduleLoader 上方法 
  25.         return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null); 
  26.     }, 
  27.     resolveId: getDeprecatedContextHandler(...), 
  28.     setAssetSource: fileEmitter.setAssetSource, 
  29.     warn(warning) {} 
  30. }; 

插件的缓存

插件还提供缓存的能力,利用了闭包实现的非常巧妙。

  1. export function createPluginCache(cache: SerializablePluginCache): PluginCache { 
  2.  // 利用闭包将 cache 缓存 
  3.  return { 
  4.   has(id: string) { 
  5.    const item = cache[id]; 
  6.    if (!item) return false
  7.    item[0] = 0; // 如果访问了,那么重置访问过期次数,猜测:就是说明用户有意向主动去使用 
  8.    return true
  9.   }, 
  10.   get(id: string) { 
  11.    const item = cache[id]; 
  12.    if (!item) return undefined; 
  13.    item[0] = 0; // 如果访问了,那么重置访问过期次数 
  14.    return item[1]; 
  15.   }, 
  16.   set(id: string, value: any) { 
  17.             // 存储单位是数组,第一项用来标记访问次数 
  18.    cache[id] = [0, value]; 
  19.   }, 
  20.   delete(id: string) { 
  21.    return delete cache[id]; 
  22.   } 
  23.  }; 

然后创建缓存后,会添加在插件上下文中:

  1. import createPluginCache from 'createPluginCache'
  2.  
  3. const cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null))); 
  4.  
  5. const context = { 
  6.  // ... 
  7.     cache: cacheInstance, 
  8.     // ... 

之后我们就可以在插件中就可以使用 cache 进行插件环境下的缓存,进一步提升打包效率:

  1. function testPlugin() { 
  2.   return { 
  3.     name"test-plugin"
  4.     buildStart() { 
  5.       if (!this.cache.has("prev")) { 
  6.         this.cache.set("prev""上一次插件执行的结果"); 
  7.       } else { 
  8.         // 第二次执行 rollup 的时候会执行 
  9.         console.log(this.cache.get("prev")); 
  10.       } 
  11.     }, 
  12.   }; 
  13. let cache; 
  14. async function build() { 
  15.   const chunks = await rollup.rollup({ 
  16.     input: "src/main.js"
  17.     plugins: [testPlugin()], 
  18.     // 需要传递上次的打包结果 
  19.     cache, 
  20.   }); 
  21.   cache = chunks.cache; 
  22.  
  23. build().then(() => { 
  24.   build(); 
  25. }); 

总结

恭喜你,把 rollup 那么几种钩子函数都熬着看过来了,并且又梳理了一遍 rollup.rollup() 打包流程。总结几点输出,康康我们学到了什么:

rollup 的插件本质是一个处理函数,返回一个对象。返回的对象包含一些属性(如 name),和不同阶段的钩子函数(构建 build 和输出 output 阶段),以实现插件内部的功能;

关于返回的对象,在插件返回对象中的钩子函数中,大多数的钩子函数定义了 插件的调用时机和调用方式,只有 runHook(Sync)钩子真正执行了插件;

关于插件调用时机和调用方法的触发取决于打包流程,在此我们通过图 1 流程图也梳理了一遍 rollup.rollup() 打包流程;

插件原理都讲完了,插件调用当然 so easy,一个函数谁还不会用呢?而对于简单插件函数的开发页也不仅仅是单纯模仿,也可以做到心中有数了!

在实际的插件开发中,我们会进一步用到这些知识并一一掌握,至少写出 bug 的时候,梳理一遍插件原理,再进一步内化吸收,就能更快的定位问题了。在开发中如果有想法,就可以着手编写自己的 rollup 插件啦!

 

责任编辑:姜华 来源: 微医大前端技术
相关推荐

2020-09-08 18:37:49

TypeScript开发前端

2015-04-07 11:05:15

VMwareOpenStack

2021-07-12 07:33:31

Nacos微服务管理

2019-09-01 21:15:51

思科安全零信任云安全

2022-02-13 23:00:48

前端微前端qiankun

2023-04-06 08:01:30

RustMutex

2021-06-30 07:51:09

新项目领域建模

2011-03-22 16:55:53

LAMPWAMP

2021-02-05 09:00:00

开发IT事件管理

2021-08-07 21:51:17

服务器网站部署

2023-01-12 22:00:48

2013-12-18 13:30:19

Linux运维Linux学习Linux入门

2022-10-28 08:14:44

rollup打包工具库​

2021-08-15 22:52:30

前端H5拼图

2022-05-25 10:28:35

模型AI

2010-09-03 13:50:12

路由器DHCP功能

2022-01-13 08:13:14

Vue3 插件Vue应用

2020-09-24 11:46:03

Promise

2015-10-13 14:12:30

技术技术栈

2021-09-15 09:57:01

组件库设计AR
点赞
收藏

51CTO技术栈公众号