rollup 中文官方
rollup 汇总插件、软件包和资源
rollup 汇总官方插件
terser
压缩 @rollup/plugin-terser 配置:
-
defaults(default:true) -- Passfalseto disable most default enabledcompresstransforms. Useful when you only want to enable a fewcompressoptions 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}becomesm:()=>x. To do this to regular ES5 functions which don't usethisorarguments, seeunsafe_arrows. -
arguments(default:false) -- replacearguments[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 whenunsafe_comps), attempts to negate binary nodes, e.g.a = !b && !c && !d && !e → a=!(b||c||d||e)etc. Note:comparisonsworks best withlhs_constantsenabled. -
computed_props(default:true) -- Transforms constant computed properties into regular ones:{["computed"]: 1}is converted to{computed: 1}. -
conditionals(default:true) -- apply optimizations forif-s and conditional expressions -
dead_code(default:true) -- remove unreachable code -
directives(default:true) -- remove redundant or non-standard directives -
drop_console(default:false) -- Passtrueto discard calls toconsole.*functions. If you only want to discard a portion of console, you can pass an array like this['log', 'info'], which will only discardconsole.log、console.info. -
drop_debugger(default:true) -- removedebugger;statements -
ecma(default:5) -- Pass2015or greater to enablecompressoptions that will transform ES5 code into smaller ES6+ equivalent forms. -
evaluate(default:true) -- attempt to evaluate constant expressions -
expression(default:false) -- Passtrueto preserve completion values from terminal statements withoutreturn, 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 tof(1, 2);. Note:hoist_propsworks best withmangleenabled, thecompressoptionpassesset to2or higher, and thecompressoptiontoplevelenabled. -
hoist_vars(default:false) -- hoistvardeclarations (this isfalseby 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/returnstatement:false-- same as00-- disabled inlining1-- inline simple functions2-- inline functions with arguments3-- inline functions with arguments and variablestrue-- same as3
-
join_vars(default:true) -- join consecutivevar,letandconststatements -
keep_classnames(default:false) -- Passtrueto prevent the compressor from discarding class names. Pass a regular expression to only keep class names matching that regex. See also: thekeep_classnamesmangle option. -
keep_fargs(default:true) -- Prevents the compressor from discarding unused function arguments. You need this for code which relies onFunction.length. -
keep_fnames(default:false) -- Passtrueto prevent the compressor from discarding function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying onFunction.prototype.name. See also: thekeep_fnamesmangle option. -
keep_infinity(default:false) -- Passtrueto preventInfinityfrom being compressed into1/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 fordo,whileandforloops when we can statically determine the condition. -
module(defaultfalse) -- Passtruewhen compressing an ES6 module. Strict mode is implied and thetopleveloption 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 examplefoo["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 instancevar q = Math.floor(a/b). If variableqis not used elsewhere, Terser will drop it, but will still keep theMath.floor(a/b), not knowing what it does. You can passpure_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 passtruefor this, Terser will assume that object property access (e.g.foo.barorfoo["bar"]) doesn't have any side effects. Specify"strict"to treatfoo.baras side-effect-free only whenfoois certain to not throw, i.e. notnullorundefined. -
pure_new(default:false) -- Set totrueto assumenew 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 onreduce_varsbeing 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 totruethen the defaultsequenceslimit is200. Set option tofalseor0to disable. The smallestsequenceslength is2. Asequencesvalue of1is grandfathered to be equivalent totrueand as such means200. On rare occasions the default sequences limit leads to very slow compress times in which case a value of20or 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 unreachableswitchbranches -
toplevel(default:false) -- drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (falseby default,trueto drop both unreferenced functions and variables) -
top_retain(default:null) -- prevent specific toplevel functions and variables fromunusedremoval (can be array, comma-separated, RegExp or function. Impliestoplevel) -
typeofs(default:true) -- Transformstypeof foo == "undefined"intofoo === void 0. Note: recommend to set this value tofalsefor 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 referencethis. Note: it is not always safe to perform this conversion if code relies on the the function having aprototype, which arrow functions lack. This transform requires that theecmacompress option is set to2015or 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 likeget, orvalueOf. This could cause change in execution order after operands in the comparison are switching. Compression only works if bothcomparisonsandunsafe_compsare both set to true. -
unsafe_Function(default:false) -- compress and mangleFunction(args, code)when bothargsandcodeare string literals. -
unsafe_math(default:false) -- optimize numerical expressions like2 * x * 3into6 * x, which may give imprecise floating point results. -
unsafe_symbols(default:false) -- removes keys from native Symbol declarations, e.gSymbol("kDog")becomesSymbol(). -
unsafe_methods(default: false) -- Converts{ m: function(){} }to{ m(){} }.ecmamust be set to6or greater to enable this transform. Ifunsafe_methodsis 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 tonewthe former function. -
unsafe_proto(default:false) -- optimize expressions likeArray.prototype.slice.call(a)into[].slice.call(a) -
unsafe_regexp(default:false) -- enable substitutions of variables withRegExpvalues the same way as if they are constants. -
unsafe_undefined(default:false) -- substitutevoid 0if there is a variable namedundefinedin 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
- 常用于对单独模块通过
ast对code进行转换操作并返回{ ast, map, ast }对象对源代码修改、返回null交由其他插件钩子处理,以官方strip插件为例对源码进行debugger语句方法消除:
moduleParsed
- 当每个模块被完全解析后调用,传入的参数为
this.getModuleInfo返回值对于一些动态加载模块和元信息并不完成,如果需要完整的模块信息可在buildEnd中获取