Rollup 个人纪录

205 阅读9分钟

rollup 中文官方

rollup 汇总插件、软件包和资源

rollup 汇总官方插件

terser

压缩 @rollup/plugin-terser 配置:

  • defaults (default: true) -- Pass false to disable most default enabled compress transforms. Useful when you only want to enable a few compress options while disabling the rest.

  • arrows (default: true) -- Class and object literal methods are converted will also be converted to arrow expressions if the resultant code is shorter: m(){return x} becomes m:()=>x. To do this to regular ES5 functions which don't use this or arguments, see unsafe_arrows.

  • arguments (default: false) -- replace arguments[index] with function parameter name whenever possible.

  • booleans (default: true) -- various optimizations for boolean context, for example !!a ? b : c → a ? b : c

  • booleans_as_integers (default: false) -- Turn booleans into 0 and 1, also makes comparisons with booleans use == and != instead of === and !==.

  • collapse_vars (default: true) -- Collapse single-use non-constant variables, side effects permitting.

  • comparisons (default: true) -- apply certain optimizations to binary nodes, e.g. !(a <= b) → a > b (only when unsafe_comps), attempts to negate binary nodes, e.g. a = !b && !c && !d && !e → a=!(b||c||d||e) etc. Note: comparisons works best with lhs_constants enabled.

  • computed_props (default: true) -- Transforms constant computed properties into regular ones: {["computed"]: 1} is converted to {computed: 1}.

  • conditionals (default: true) -- apply optimizations for if-s and conditional expressions

  • dead_code (default: true) -- remove unreachable code

  • directives (default: true) -- remove redundant or non-standard directives

  • drop_console (default: false) -- Pass true to discard calls to console.* functions. If you only want to discard a portion of console, you can pass an array like this ['log', 'info'], which will only discard console.log、 console.info.

  • drop_debugger (default: true) -- remove debugger; statements

  • ecma (default: 5) -- Pass 2015 or greater to enable compress options that will transform ES5 code into smaller ES6+ equivalent forms.

  • evaluate (default: true) -- attempt to evaluate constant expressions

  • expression (default: false) -- Pass true to preserve completion values from terminal statements without return, e.g. in bookmarklets.

  • global_defs (default: {}) -- see conditional compilation

  • hoist_funs (default: false) -- hoist function declarations

  • hoist_props (default: true) -- hoist properties from constant object and array literals into regular variables subject to a set of constraints. For example: var o={p:1, q:2}; f(o.p, o.q); is converted to f(1, 2);. Note: hoist_props works best with mangle enabled, the compress option passes set to 2 or higher, and the compress option toplevel enabled.

  • hoist_vars (default: false) -- hoist var declarations (this is false by default because it seems to increase the size of the output in general)

  • if_return (default: true) -- optimizations for if/return and if/continue

  • inline (default: true) -- inline calls to function with simple/return statement:

    • false -- same as 0
    • 0 -- disabled inlining
    • 1 -- inline simple functions
    • 2 -- inline functions with arguments
    • 3 -- inline functions with arguments and variables
    • true -- same as 3
  • join_vars (default: true) -- join consecutive varlet and const statements

  • keep_classnames (default: false) -- Pass true to prevent the compressor from discarding class names. Pass a regular expression to only keep class names matching that regex. See also: the keep_classnames mangle option.

  • keep_fargs (default: true) -- Prevents the compressor from discarding unused function arguments. You need this for code which relies on Function.length.

  • keep_fnames (default: false) -- Pass true to prevent the compressor from discarding function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying on Function.prototype.name. See also: the keep_fnames mangle option.

  • keep_infinity (default: false) -- Pass true to prevent Infinity from being compressed into 1/0, which may cause performance issues on Chrome.

  • lhs_constants (default: true) -- Moves constant values to the left-hand side of binary nodes. foo == 42 → 42 == foo

  • loops (default: true) -- optimizations for dowhile and for loops when we can statically determine the condition.

  • module (default false) -- Pass true when compressing an ES6 module. Strict mode is implied and the toplevel option as well.

  • negate_iife (default: true) -- negate "Immediately-Called Function Expressions" where the return value is discarded, to avoid the parens that the code generator would insert.

  • passes (default: 1) -- The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time.

  • properties (default: true) -- rewrite property access using the dot notation, for example foo["bar"] → foo.bar

  • pure_funcs (default: null) -- You can pass an array of names and Terser will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instance var q = Math.floor(a/b). If variable q is not used elsewhere, Terser will drop it, but will still keep the Math.floor(a/b), not knowing what it does. You can pass pure_funcs: [ 'Math.floor' ] to let it know that this function won't produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower).

  • pure_getters (default: "strict") -- If you pass true for this, Terser will assume that object property access (e.g. foo.bar or foo["bar"]) doesn't have any side effects. Specify "strict" to treat foo.bar as side-effect-free only when foo is certain to not throw, i.e. not null or undefined.

  • pure_new (default: false) -- Set to true to assume new X() never has side effects.

  • reduce_vars (default: true) -- Improve optimization on variables assigned with and used as constant values.

  • reduce_funcs (default: true) -- Inline single-use functions when possible. Depends on reduce_vars being enabled. Disabling this option sometimes improves performance of the output code.

  • sequences (default: true) -- join consecutive simple statements using the comma operator. May be set to a positive integer to specify the maximum number of consecutive comma sequences that will be generated. If this option is set to true then the default sequences limit is 200. Set option to false or 0 to disable. The smallest sequences length is 2. A sequences value of 1 is grandfathered to be equivalent to true and as such means 200. On rare occasions the default sequences limit leads to very slow compress times in which case a value of 20 or less is recommended.

  • side_effects (default: true) -- Remove expressions which have no side effects and whose results aren't used.

  • switches (default: true) -- de-duplicate and remove unreachable switch branches

  • toplevel (default: false) -- drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (false by default, true to drop both unreferenced functions and variables)

  • top_retain (default: null) -- prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel)

  • typeofs (default: true) -- Transforms typeof foo == "undefined" into foo === void 0. Note: recommend to set this value to false for IE10 and earlier versions due to known issues.

  • unsafe (default: false) -- apply "unsafe" transformations (details).

  • unsafe_arrows (default: false) -- Convert ES5 style anonymous function expressions to arrow functions if the function body does not reference this. Note: it is not always safe to perform this conversion if code relies on the the function having a prototype, which arrow functions lack. This transform requires that the ecma compress option is set to 2015 or greater.

  • unsafe_comps (default: false) -- Reverse < and <= to > and >= to allow improved compression. This might be unsafe when an at least one of two operands is an object with computed values due the use of methods like get, or valueOf. This could cause change in execution order after operands in the comparison are switching. Compression only works if both comparisons and unsafe_comps are both set to true.

  • unsafe_Function (default: false) -- compress and mangle Function(args, code) when both args and code are string literals.

  • unsafe_math (default: false) -- optimize numerical expressions like 2 * x * 3 into 6 * x, which may give imprecise floating point results.

  • unsafe_symbols (default: false) -- removes keys from native Symbol declarations, e.g Symbol("kDog") becomes Symbol().

  • unsafe_methods (default: false) -- Converts { m: function(){} } to { m(){} }ecma must be set to 6 or greater to enable this transform. If unsafe_methods is a RegExp then key/value pairs with keys matching the RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a "<method name> is not a constructor" TypeError should any code try to new the former function.

  • unsafe_proto (default: false) -- optimize expressions like Array.prototype.slice.call(a) into [].slice.call(a)

  • unsafe_regexp (default: false) -- enable substitutions of variables with RegExp values the same way as if they are constants.

  • unsafe_undefined (default: false) -- substitute void 0 if there is a variable named undefined in scope (variable name will be mangled, typically reduced to a single character)

  • unused (default: true) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to "keep_assign")

插件开发

插件概述

  • Rollup 插件是一个对象,具有 属性构建钩子 和 输出生成钩子 中的一个或多个,并遵循我们的 约定
  • 插件允许你通过例如在打包之前进行转译代码或在node_modules文件夹中查找第三方模块来自定义 Rollup 的行为

插件约定

  • 插件应该有一个明确的名称,并以rollup-plugin-作为前缀。
  • package.json中包含rollup-plugin关键字。
  • 插件应该被测试,我们推荐 mocha 或 ava,它们支持 Promise。
  • 可能的话,使用异步方法,例如 fs.readFile 而不是 fs.readFileSync
  • 用英文文档描述你的插件。
  • 确保如果适当,你的插件输出正确的源映射。
  • 如果插件使用“虚拟模块”(例如用于辅助函数),请使用\0前缀模块 ID。这可以防止其他插件尝试处理它。

插件开发工具库

@rollup/pluginutils是一个官方提供的Rollup插件开发工具库,它提供了一些实用的函数和工具,用于简化插件开发过程中的一些常见任务

插件有不同种类的钩子

不同类型的钩子

  • async:该钩子也可以返回一个解析为相同类型的值的 Promise;否则,该钩子被标记为 sync
  • first:如果有多个插件实现此钩子,则钩子按顺序运行,直到钩子返回一个不是 null 或 undefined 的值。
  • sequential:如果有多个插件实现此钩子,则所有这些钩子将按指定的插件顺序运行。如果钩子是 async,则此类后续钩子将等待当前钩子解决后再运行。
  • parallel:如果有多个插件实现此钩子,则所有这些钩子将按指定的插件顺序运行。如果钩子是 async,则此类后续钩子将并行运行,而不是等待当前钩子。

除了函数钩子之外,钩子也可以是对象,在这种情况下,必须指定为 handler

  • order: "pre" | "post" | null
    如果有多个插件实现此钩子,则可以先运行此插件("pre"),最后运行此插件("post"),或在用户指定的位置运行(没有值或 null

  • sequential: boolean 不要与其他插件的相同钩子并行运行此钩子。仅可用于 parallel 钩子。

上面类型的钩子 例子:

import { resolve } from 'node:path';
import { readdir } from 'node:fs/promises';

export default function getFilesOnDisk() {
	return {
		name: 'getFilesOnDisk',
          resolveId ( source ) {  // 这边是钩子
              if (source === 'virtual-module') { 
                  return source; // rollup 不应该查询其他插件或文件系统 return null// other ids 正常处理 
          }, 
		writeBundle: { // 这边是钩子
			sequential: true, // 这边是 sequential 类型
			order: 'post', // 这边是 order 类型
			async handler({ dir }) { // 这边是 async 类型
				const topLevelFiles = await readdir(resolve(dir));
				console.log(topLevelFiles);
			}
		}
	};
} 

插件构建钩子

  • 构建阶段的第一个钩子是 options,最后一个钩子始终是 buildEnd。如果有构建错误,则在此之后将调用 closeBundle

  • 在监视模式下,watchChange 钩子可以在任何时候触发,以通知当前运行生成输出后将触发新的运行。另外,当监视器关闭时,closeWatcher 钩子将被触发。

options

  • 用于修改或操控配置在未被rollup.rollup()接收执行之前触发,读取配置的场景更推荐使用buildStart因为可能存在多个options插件对配置进行了修改

buildStart

  • rollup.rollup()被调用时触发,此时所有插件的options都已经处理并转换过可以在此钩子访问最终的配置信息(包含默认配置)

resolveld

  • 当模块被引用解析时被调用,一般用做对引入模块的信息进行修改处理并在load钩子中用作自定义处理

load

  • 自定义加载器,可以返回指定代码片段或者{ code, ast, map }对象,以官方virtual插件为例,引入对应虚拟模块返回定义的代码:

shoukdTranformCachedModule

  • 如果load钩子加载的代码与缓存副本中的相同则跳过transform钩子使用模块缓存并交由moduleParsed钩子,如果shouldTransformCachedModule返回true则从缓存中删除此模块并重新执行transform

transform

  • 常用于对单独模块通过astcode进行转换操作并返回{ ast, map, ast }对象对源代码修改、返回null交由其他插件钩子处理,以官方strip插件为例对源码进行debugger语句方法消除:

moduleParsed

  • 当每个模块被完全解析后调用,传入的参数为this.getModuleInfo返回值对于一些动态加载模块和元信息并不完成,如果需要完整的模块信息可在buildEnd中获取

resolveDaynamiclmport

buildEnd

image.png

插件输出生成钩子

image.png

插件上下文