配置选项
核心功能
external
类型 | (string | RegExp)[]| RegExp| string| (id: string, parentId: string, isResolved: boolean) => boolean |
---|---|
CLI | -e /--external <external-id,another-external-id,...> |
一个函数,接收一个 id
并返回 true
(外部)或 false
(非外部),或一个模块 ID Array
,或用于匹配模块 ID 的正则表达式,这些模块 ID 应保留在包外部。也可以只是一个 ID 或正则表达式。匹配的 ID 应为以下之一
- 外部依赖项的名称,与导入语句中完全相同。即,要将
import "dependency.js"
标记为外部,请使用"dependency.js"
,而要将import "dependency"
标记为外部,请使用"dependency"
。 - 已解析的 ID(如文件的绝对路径)。
// rollup.config.js
import { fileURLToPath } from 'node:url';
export default {
//...,
external: [
'some-externally-required-library',
fileURLToPath(
new URL(
'src/some-local-file-that-should-not-be-bundled.js',
import.meta.url
)
),
/node_modules/
]
};
请注意,如果你想通过 /node_modules/
正则表达式过滤掉包导入,例如 import {rollup} from 'rollup'
,你需要使用 @rollup/plugin-node-resolve 之类的工具,先将导入解析为 node_modules
。
当作为命令行参数提供时,它应为一个 ID 逗号分隔列表
rollup -i src/main.js ... -e foo,bar,baz
提供一个函数时,它将使用三个参数 (id, parent, isResolved)
调用,这可以让你更精细地控制
id
是所讨论模块的 idparent
是执行导入的模块的 idisResolved
表示id
是否已通过插件等解析
创建 iife
或 umd
包时,你需要通过 output.globals
选项提供全局变量名称来替换外部导入。
如果相对导入(即以 ./
或 ../
开头)标记为“外部”,rollup 将在内部将 id 解析为绝对文件系统位置,以便合并外部模块的不同导入。当写入结果包时,导入将再次转换为相对导入。示例
// input
// src/main.js (entry point)
import x from '../external.js';
import './nested/nested.js';
console.log(x);
// src/nested/nested.js
// the import would point to the same file if it existed
import x from '../../external.js';
console.log(x);
// output
// the different imports are merged
import x from '../external.js';
console.log(x);
console.log(x);
转换回相对导入的操作就像 output.file
或 output.dir
与入口点位于同一位置,或者如果有多个入口点,则与所有入口点的公共基础目录位于同一位置一样。
input
类型 | string | string []| { [entryName: string]: string } |
---|---|
CLI | -i /--input <filename> |
包的入口点(例如,您的 main.js
或 app.js
或 index.js
)。如果您提供入口点数组或将名称映射到入口点的对象,它们将被捆绑到单独的输出块中。除非使用 output.file
选项,否则生成的块名称将遵循 output.entryFileNames
选项。使用对象表单时,文件名中的 [name]
部分将是对象属性的名称,而对于数组表单,它将是入口点的文件名。
请注意,在使用对象表单时,可以通过在名称中添加 /
来将入口点放入不同的子文件夹中。以下内容将生成至少两个入口块,名称为 entry-a.js
和 entry-b/index.js
,即文件 index.js
放在 entry-b
文件夹中
// rollup.config.js
export default {
...,
input: {
a: 'src/main-a.js',
'b/index': 'src/main-b.js'
},
output: {
...,
entryFileNames: 'entry-[name].js'
}
};
如果您想将一组文件转换为另一种格式,同时保持文件结构和导出签名,建议的方法(而不是使用 output.preserveModules
,它可能会对导出进行 tree-shake 以及发出由插件创建的虚拟文件)是将每个文件变成一个入口点。您可以动态地执行此操作,例如通过 glob
包
import { globSync } from 'glob';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
export default {
input: Object.fromEntries(
globSync('src/**/*.js').map(file => [
// This remove `src/` as well as the file extension from each
// file, so e.g. src/nested/foo.js becomes nested/foo
path.relative(
'src',
file.slice(0, file.length - path.extname(file).length)
),
// This expands the relative paths to absolute paths, so e.g.
// src/nested/foo becomes /project/src/nested/foo.js
fileURLToPath(new URL(file, import.meta.url))
])
),
output: {
format: 'es',
dir: 'dist'
}
};
如果某个插件在 buildStart
钩子的末尾至少发出一个块(使用 this.emitFile
),则可以省略该选项。
使用命令行界面时,可以通过多次使用该选项来提供多个输入。当作为第一个选项提供时,它等效于不以 --input
为前缀
rollup --format es --input src/entry1.js --input src/entry2.js
# is equivalent to
rollup src/entry1.js src/entry2.js --format es
可以通过向提供的值添加 =
来命名块
rollup main=src/entry1.js other=src/entry2.js --format es
可以通过使用引号来指定包含空格的文件名
rollup "main entry"="src/entry 1.js" "src/other entry.js" --format es
output.dir
类型 | string |
---|---|
CLI | -d /--dir <dirname> |
放置所有生成块的目录。如果生成多个块,则此选项是必需的。否则,可以使用 file
选项代替。
output.file
类型 | string |
---|---|
CLI | -o /--file <filename> |
要写入的文件。如果适用,还将用于生成源映射。仅当生成不超过一个块时才能使用。
output.format
类型 | string |
---|---|
CLI | -f /--format <formatspecifier> |
默认 | "es" |
指定生成包的格式。以下之一
amd
– 异步模块定义,与 RequireJS 等模块加载器一起使用cjs
– CommonJS,适用于 Node 和其他捆绑器(别名:commonjs
)es
– 将包保留为 ES 模块文件,适用于其他捆绑器和在现代浏览器中作为<script type=module>
标记包含(别名:esm
、module
)iife
– 一个自执行函数,适合作为<script>
标记包含。(如果你想为你的应用程序创建一个包,你可能想使用这个)。“iife”代表“立即调用的 函数表达式”umd
– 通用模块定义,作为amd
、cjs
和iife
三合一system
– SystemJS 加载器的本机格式(别名:systemjs
)
output.globals
类型 | { [id: string]: string }| ((id: string) => string) |
---|---|
CLI | -g /--globals <external-id:variableName,another-external-id:anotherVariableName,...> |
指定 umd
/iife
包中外部导入所需的 id: variableName
对。例如,在如下情况下…
import $ from 'jquery';
…我们想告诉 Rollup jquery
是外部的,并且 jquery
模块 ID 等于全局 $
变量
// rollup.config.js
export default {
...,
external: ['jquery'],
output: {
format: 'iife',
name: 'MyBundle',
globals: {
jquery: '$'
}
}
};
/*
var MyBundle = (function ($) {
// code goes here
}($));
*/
或者,提供一个函数,将外部模块 ID 转换为全局变量名称。
当作为命令行参数给出时,它应该是 id:variableName
对的逗号分隔列表
rollup -i src/main.js ... -g jquery:$,underscore:_
要告知 Rollup 应将本地文件替换为全局变量,请使用绝对 ID
// rollup.config.js
import { fileURLToPath } from 'node:url';
const externalId = fileURLToPath(
new URL(
'src/some-local-file-that-should-not-be-bundled.js',
import.meta.url
)
);
export default {
//...,
external: [externalId],
output: {
format: 'iife',
name: 'MyBundle',
globals: {
[externalId]: 'globalVariable'
}
}
};
output.name
类型 | string |
---|---|
CLI | -n /--name <variableName> |
对于导出值的 iife
/umd
捆绑包而言,这是必需的,在这种情况下,它是表示捆绑包的全局变量名。同一页面上的其他脚本可以使用此变量名来访问捆绑包的导出内容。
// rollup.config.js
export default {
...,
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyBundle'
}
};
// var MyBundle = (function () {...
支持命名空间,即您的名称可以包含点。生成的捆绑包将包含命名空间所需的设置。
rollup -n "a.b.c"
/* ->
this.a = this.a || {};
this.a.b = this.a.b || {};
this.a.b.c = ...
*/
output.plugins
类型 | MaybeArray<MaybePromise<OutputPlugin | void>> |
---|
仅将插件添加到此输出。有关如何使用特定于输出的插件的更多信息,请参见 使用输出插件,有关如何编写自己的插件的信息,请参见 插件。对于从包导入的插件,请记住调用导入的插件函数(即 commonjs()
,而不仅仅是 commonjs
)。虚假插件将被忽略,这可用于轻松激活或停用插件。嵌套插件将被展平。异步插件将被等待并解析。
并非所有插件都可以在此处使用。output.plugins
仅限于仅使用在 bundle.generate()
或 bundle.write()
(即在 Rollup 的主要分析完成后)期间运行的钩子的插件。如果您是插件作者,请参见 输出生成钩子 以了解可以使用哪些钩子。
以下内容将缩小其中一个输出
// rollup.config.js
import terser from '@rollup/plugin-terser';
export default {
input: 'main.js',
output: [
{
file: 'bundle.js',
format: 'es'
},
{
file: 'bundle.min.js',
format: 'es',
plugins: [terser()]
}
]
};
plugins
类型 | MaybeArray<MaybePromise<Plugin | void>> |
---|
有关如何使用插件的更多信息,请参见 使用插件,有关如何编写自己的插件的信息,请参见 插件(试一试,这并不像听起来那么困难,而且极大地扩展了您可以使用 Rollup 执行的操作)。对于从包导入的插件,请记住调用导入的插件函数(即 commonjs()
,而不仅仅是 commonjs
)。虚假插件将被忽略,这可用于轻松激活或停用插件。嵌套插件将被展平。异步插件将被等待并解析。
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
const isProduction = process.env.NODE_ENV === 'production';
export default (async () => ({
input: 'main.js',
plugins: [
resolve(),
commonjs(),
isProduction && (await import('@rollup/plugin-terser')).default()
],
output: {
file: 'bundle.js',
format: 'cjs'
}
}))();
(此示例还演示了如何使用异步 IIFE 和动态导入来避免不必要的模块加载,这可能会意外地变慢。)
高级功能
cache
类型 | RollupCache | 布尔值 |
---|---|
默认 | true |
上一个包的 cache
属性。在监视模式下使用它来加速后续的构建 — Rollup 将仅重新分析已更改的模块。将此选项明确设置为 false
将阻止在包上生成 cache
属性,并禁用插件的缓存。
const rollup = require('rollup');
let cache;
async function buildWithCache() {
const bundle = await rollup.rollup({
cache // is ignored if falsy
// ... other input options
});
cache = bundle.cache; // store the cache object of the previous build
return bundle;
}
buildWithCache()
.then(bundle => {
// ... do something with the bundle
})
.then(() => buildWithCache()) // will use the cache of the previous build
.then(bundle => {
// ... do something with the bundle
});
logLevel
类型 | LogLevel | "silent" |
---|---|
CLI | --logLevel <level> |
默认 | "info" |
确定要处理哪些日志。有关可用的日志级别,请参见 onLog
。默认 logLevel
为 "info"
,这意味着将处理信息和警告日志,而调试日志将被忽略,这意味着它们既不会传递给插件 onLog
钩子,也不会传递给 onLog
选项或打印到控制台。
在使用 CLI 时,错误仍将打印到控制台,因为它们不会通过日志记录系统进行处理。有关如何禁止错误日志,请参见 --silent
标志。
makeAbsoluteExternalsRelative
类型 | 布尔值 | "ifRelativeSource" |
---|---|
CLI | --makeAbsoluteExternalsRelative /--no-makeAbsoluteExternalsRelative |
默认 | "ifRelativeSource" |
确定是否应在输出中将绝对外部路径转换为相对路径。这不仅适用于源中绝对的路径,还适用于由插件或 Rollup 核心解析为绝对路径的路径。
对于 true
,外部导入(如 import "/Users/Rollup/project/relative.js"
)将转换为相对路径。在将绝对路径转换为相对路径时,Rollup 不会考虑 file
或 dir
选项,因为这些选项可能不存在,例如对于使用 JavaScript API 进行构建的情况。相反,它假定生成的包的根目录位于包含在包中的所有模块的公共共享父目录中。假设所有模块的公共父目录是 "/Users/Rollup/project"
,那么上面的导入在输出中很可能将转换为 import "./relative.js"
。如果输出块本身嵌套在子目录中,例如选择 chunkFileNames: "chunks/[name].js"
,则导入将为 "../relative.js"
。
如前所述,这也适用于最初的相对导入(如 import "./relative.js"
),这些导入在被 external
选项标记为外部之前已解析为绝对路径。
一个常见的问题是,此机制还将适用于 import "/absolute.js'"
等导入,从而导致输出中出现意外的相对路径。
对于这种情况,"ifRelativeSource"
检查原始导入是否为相对导入,然后才将其转换为输出中的相对导入。选择 false
将在输出中保留所有路径为绝对路径。
请注意,当使用 external
选项将相对路径直接标记为“外部”时,它将是输出中的相同相对路径。当它首先通过插件或 Rollup 核心解析,然后标记为外部时,将应用上述逻辑。
maxParallelFileOps
类型 | 数字 |
---|---|
CLI | --maxParallelFileOps <number> |
默认 | 20 |
限制 Rollup 在读取模块或写入块时并行打开的文件数。如果没有限制或值足够高,则构建可能会因“EMFILE:打开的文件过多”而失败。这取决于操作系统允许打开的文件句柄数。
onLog
类型 | (level: LogLevel, log: RollupLog, defaultHandler: LogOrStringHandler) => void; |
---|
type LogLevel = 'warn' | 'info' | 'debug';
type LogOrStringHandler = (
level: LogLevel | 'error',
log: string | RollupLog
) => void;
// All possible properties, actual properties depend on log
interface RollupLog {
binding?: string;
cause?: Error;
code?: string;
exporter?: string;
frame?: string; // always printed by the CLI
hook?: string;
id?: string; // always printed by the CLI
ids?: string[];
loc?: {
column: number;
file?: string;
line: number;
}; // always printed by the CLI if id is present
message: string; // the actual message, always printed by the CLI
meta?: any; // add custom plugin properties to logs
names?: string[];
plugin?: string; // added by Rollup for plugin logs, only printed for warnings
pluginCode?: string; // added by Rollup for plugin logs that contain a code
pos?: number;
reexporter?: string;
stack?: string; // url for additional information, always printed by the CLI
url?: string;
}
拦截日志消息的函数。如果没有提供,日志将打印到控制台,Rollup CLI 会聚合某些 "warn"
日志,并在构建后打印合并的警告以减少噪音。使用 --silent
CLI 选项时也会触发此处理程序。
该函数接收三个参数:日志级别、日志对象和默认处理程序。日志对象至少有一个code
和一个message
属性,允许你控制不同种类的日志的处理方式。其他属性会根据日志类型添加。请参阅utils/logs.ts
以获取内置错误和日志的完整列表,以及它们的代码和属性。
如果未调用默认处理程序,则不会将日志打印到控制台。此外,你可以通过使用不同的级别调用默认处理程序来更改日志级别。使用附加级别"error"
将使日志变成一个抛出的错误,该错误具有附加的所有日志属性。
// rollup.config.js
export default {
//...
onLog(level, log, handler) {
if (log.code === 'CIRCULAR_DEPENDENCY') {
return; // Ignore circular dependency warnings
}
if (level === 'warn') {
handler('error', log); // turn other warnings into errors
} else {
handler(level, log); // otherwise, just print the log
}
}
};
如果日志被logLevel
选项过滤掉,则不会调用此处理程序。即默认情况下,"debug"
日志将被吞没。
一些日志还具有loc
属性和frame
属性,允许你找到日志的来源
// rollup.config.js
export default {
//...
onLog(level, { loc, frame, message }) {
if (loc) {
console.warn(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
if (frame) console.warn(frame);
} else {
console.warn(message);
}
}
};
onwarn
类型 | (warning: RollupLog, defaultHandler: (warning: string | RollupLog) => void) => void; |
---|
一个将拦截警告消息的函数。它与onLog
非常相似,但仅接收警告。如果调用了默认处理程序,则日志将作为警告处理。如果同时提供了onLog
和onwarn
处理程序,则只有当onLog
使用warn
的level
调用其默认处理程序时,才会调用onwarn
处理程序。
请参阅onLog
了解更多信息。
output.assetFileNames
类型 | string| ((assetInfo: AssetInfo) => string) |
---|---|
CLI | --assetFileNames <pattern> |
默认 | "assets/[name]-[hash][extname]" |
用于命名要包含在构建输出中的自定义已发出资产的模式,或一个针对每个资产调用的函数以返回此类模式。模式支持以下占位符
[extname]
:资产的文件扩展名,包括前导点,例如.css
。[ext]
:没有前导点的文件扩展名,例如css
。[hash]
:基于资产内容的哈希。你还可以通过例如[hash:10]
设置特定的哈希长度。默认情况下,它将创建一个 base-64 哈希。如果你需要减少字符集,请参阅output.hashCharacters
[name]
:资产的文件名,不包括任何扩展名。
正斜杠 /
可用于将文件放入子目录中。使用函数时,assetInfo
是 generateBundle
中的一个精简版本,不带 fileName
。另请参阅 output.chunkFileNames
、output.entryFileNames
。
output.banner/output.footer
类型 | string | ((chunk: ChunkInfo) => string| Promise<string>) |
---|---|
CLI | --banner /--footer <text> |
要添加到包的开头/结尾的字符串。你还可以提供一个返回 Promise
的函数,该函数解析为 string
以异步生成它(注意:banner
和 footer
选项不会破坏源映射)。
如果你提供一个函数,chunk
包含有关块的附加信息,使用与 generateBundle
钩子相同的 ChunkInfo
类型,但有以下区别
code
和map
未设置,因为该块尚未呈现。- 所有包含哈希的引用块文件名都将包含哈希占位符。这包括
fileName
、imports
、importedBindings
、dynamicImports
和implicitlyLoadedBefore
。当你在此选项返回的代码中使用这样的占位符文件名或其一部分时,Rollup 将在generateBundle
之前用实际哈希替换占位符,确保哈希反映最终生成块的实际内容,包括所有引用的文件哈希。
chunk
是可变的,在此钩子中应用的更改将传播到其他插件和生成的包。这意味着如果你在此钩子中添加或删除导入或导出,你应更新 imports
、importedBindings
和/或 exports
。
// rollup.config.js
export default {
...,
output: {
...,
banner: '/* my-library version ' + version + ' */',
footer: '/* follow me on Twitter! @rich_harris */'
}
};
另请参阅 output.intro/output.outro
。
output.chunkFileNames
类型 | string | ((chunkInfo: ChunkInfo) => string) |
---|---|
CLI | --chunkFileNames <pattern> |
默认 | "[name]-[hash].js" |
用于命名代码拆分时创建的共享块的模式,或一个按块调用的函数,用于返回此类模式。模式支持以下占位符
[format]
:输出选项中定义的渲染格式,例如es
或cjs
。[hash]
:仅基于最终生成的块的内容的哈希,包括renderChunk
中的转换和任何引用的文件哈希。您还可以通过例如[hash:10]
设置特定的哈希长度。默认情况下,它将创建一个 base-64 哈希。如果您需要减少字符集,请参阅output.hashCharacters
[name]
:块的名称。这可以通过output.manualChunks
选项或当块通过this.emitFile
由插件创建时显式设置。否则,它将从块内容中派生。
正斜杠 /
可用于将文件放置在子目录中。使用函数时,chunkInfo
是 generateBundle
中的一个精简版本,不包含依赖于文件名的属性,也没有关于已渲染模块的信息,因为渲染仅在生成文件名后发生。但是,您可以访问包含的 moduleIds
列表。另请参阅 output.assetFileNames
、output.entryFileNames
。
output.compact
类型 | 布尔值 |
---|---|
CLI | --compact /--no-compact |
默认 | false |
这将缩小 rollup 生成的包装器代码。请注意,这不会影响用户编写的代码。在捆绑预缩小的代码时,此选项很有用。
output.dynamicImportInCjs
类型 | 布尔值 |
---|---|
CLI | --dynamicImportInCjs /--no-dynamicImportInCjs |
默认 | true |
虽然 CommonJS 输出最初仅支持 require(…)
来导入依赖项,但最近的 Node 版本也开始支持 import(…)
,这是从 CommonJS 文件导入 ES 模块的唯一方法。如果此选项为 true
(这是默认值),Rollup 将在 CommonJS 输出中将外部动态导入保留为 import(…)
表达式。将其设置为 false
以使用 require(…)
语法重写动态导入。
// input
import('external').then(console.log);
// cjs output with dynamicImportInCjs: true or not set
import('external').then(console.log);
// cjs output with dynamicImportInCjs: false
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(
n,
k,
d.get
? d
: {
enumerable: true,
get: function () {
return e[k];
}
}
);
}
});
}
n.default = e;
return Object.freeze(n);
}
Promise.resolve()
.then(function () {
return /*#__PURE__*/ _interopNamespaceDefault(require('external'));
})
.then(console.log);
output.entryFileNames
类型 | string | ((chunkInfo: ChunkInfo) => string) |
---|---|
CLI | --entryFileNames <pattern> |
默认 | "[name].js" |
用于从入口点创建的块的模式,或一个按入口块调用的函数,用于返回此类模式。模式支持以下占位符
[format]
:输出选项中定义的渲染格式,例如es
或cjs
。[hash]
:仅基于最终生成的入口块的内容的哈希,包括renderChunk
中的转换和任何引用的文件哈希。您还可以通过例如[hash:10]
设置特定的哈希长度。默认情况下,它将创建一个 base-64 哈希。如果您需要减少字符集,请参阅output.hashCharacters
[name]
:入口点的文件名(无扩展名),除非使用输入的对象形式定义了不同的名称。
正斜杠 /
可用于将文件放置在子目录中。使用函数时,chunkInfo
是 generateBundle
中的一个精简版本,不包含依赖于文件名且不包含有关已渲染模块的信息的属性,因为渲染仅在生成文件名后才会发生。但是,你可以访问包含的 moduleIds
列表。另请参阅 output.assetFileNames
、output.chunkFileNames
。
设置 output.preserveModules
选项时,此模式也将用于每个文件。请注意,在这种情况下,[name]
将包含从输出根目录的相对路径,以及原始文件扩展名(如果不是 .js
、.jsx
、.mjs
、.cjs
、.ts
、.tsx
、.mts
或 .cts
之一)。
output.extend
类型 | 布尔值 |
---|---|
CLI | --extend /--no-extend |
默认 | false |
是否在 umd
或 iife
格式中扩展由 name
选项定义的全局变量。当为 true
时,全局变量将定义为 (global.name = global.name || {})
。当为 false 时,由 name
定义的全局变量将被覆盖,如 (global.name = {})
。
output.externalImportAttributes
类型 | 布尔值 |
---|---|
CLI | --externalImportAttributes /--no-externalImportAttributes |
默认 | true |
如果输出格式为 es
,是否向输出中的外部导入添加导入属性。默认情况下,属性取自输入文件,但插件稍后可以添加或删除属性。例如,import "foo" assert {type: "json"}
将导致相同的导入出现在输出中,除非该选项设置为 false
。请注意,模块的所有导入都需要具有相同属性,否则会发出警告。
output.generatedCode
类型 | "es5" | "es2015"| { arrowFunctions?: boolean, constBindings?: boolean, objectShorthand?: boolean, preset?: "es5"| "es2015", reservedNamesAsProps?: boolean, symbols?: boolean } |
---|---|
CLI | --generatedCode <preset> |
默认 | "es5" |
Rollup 可以安全地在生成代码中使用哪些语言特性。这不会转换任何用户代码,而只会更改 Rollup 在包装器和帮助器中使用的代码。你可以选择几个预设之一
"es5"
:不要使用箭头函数等 ES2015+ 特性,但不要引用用作属性的保留名称。"es2015"
:使用任何高达 ES2015 的 JavaScript 特性。
output.generatedCode.arrowFunctions
类型 | 布尔值 |
---|---|
CLI | --generatedCode.arrowFunctions /--no-generatedCode.arrowFunctions |
默认 | false |
是否为自动生成的代码片段使用箭头函数。请注意,在模块包装器等特定位置,Rollup 将继续使用括号括起来的常规函数,因为在某些 JavaScript 引擎中,这些函数将提供 明显更好的性能。
output.generatedCode.constBindings
类型 | 布尔值 |
---|---|
CLI | --generatedCode.constBindings /--no-generatedCode.constBindings |
默认 | false |
这将在特定位置和辅助函数中使用 const
而不是 var
。由于块级作用域,这将允许 Rollup 生成更高效的辅助函数。
// input
export * from 'external';
// cjs output with constBindings: false
var external = require('external');
Object.keys(external).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return external[k];
}
});
});
// cjs output with constBindings: true
const external = require('external');
for (const k in external) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
Object.defineProperty(exports, k, {
enumerable: true,
get: () => external[k]
});
}
output.generatedCode.objectShorthand
类型 | 布尔值 |
---|---|
CLI | --generatedCode.objectShorthand /--no-generatedCode.objectShorthand |
默认 | false |
允许在属性名称与值匹配时在对象中使用简写符号。
// input
const foo = 1;
export { foo, foo as bar };
// system output with objectShorthand: false
System.register('bundle', [], function (exports) {
'use strict';
return {
execute: function () {
const foo = 1;
exports({ foo: foo, bar: foo });
}
};
});
// system output with objectShorthand: true
System.register('bundle', [], function (exports) {
'use strict';
return {
execute: function () {
const foo = 1;
exports({ foo, bar: foo });
}
};
});
output.generatedCode.preset
类型 | "es5" | "es2015" |
---|---|
CLI | --generatedCode <value> |
允许在覆盖某些选项的同时选择上面列出的预设之一。
export default {
// ...
output: {
generatedCode: {
preset: 'es2015',
arrowFunctions: false
}
// ...
}
};
output.generatedCode.reservedNamesAsProps
类型 | 布尔值 |
---|---|
CLI | --generatedCode.reservedNamesAsProps /--no-generatedCode.reservedNamesAsProps |
默认 | true |
确定是否可以使用“default”等保留字作为 prop 名称而不使用引号。这将使生成的代码的语法符合 ES3。但是,请注意,为了完全符合 ES3,您可能还需要填充一些内置函数,例如 Object.keys
或 Array.prototype.forEach
。
// input
const foo = null;
export { foo as void };
// cjs output with reservedNamesAsProps: false
const foo = null;
exports['void'] = foo;
// cjs output with reservedNamesAsProps: true
const foo = null;
exports.void = foo;
output.generatedCode.symbols
类型 | 布尔值 |
---|---|
CLI | --generatedCode.symbols /--no-generatedCode.symbols |
默认 | false |
是否允许在自动生成的代码片段中使用 Symbol
。目前,这仅控制命名空间是否将 Symbol.toStringTag
属性设置为 Module
的正确值,这意味着对于命名空间,String(namespace)
记录 [object Module]
。这又用于某些库和框架中的特性检测。
// input
export const foo = 42;
// cjs output with symbols: false
const foo = 42;
exports.foo = foo;
// cjs output with symbols: true
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const foo = 42;
exports.foo = foo;
output.hashCharacters
类型 | "base64" | "base32" | "hex" |
---|---|
CLI | --hashCharacters <name> |
默认 | "base64" |
这决定了 Rollup 在文件哈希中允许使用的字符集。
- 默认的
"base64"
将使用 url 安全的 base-64 哈希,潜在字符为ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
。 "base36"
将仅使用小写字母和数字abcdefghijklmnopqrstuvwxyz0123456789
。"hex"
将创建十六进制哈希,字符为abcdef0123456789
。
output.hoistTransitiveImports
类型 | 布尔值 |
---|---|
CLI | --hoistTransitiveImports /--no-hoistTransitiveImports |
默认 | true |
默认情况下,在创建多个块时,条目块的传递导入将作为空导入添加到条目块。有关详细信息和背景,请参阅 "在代码拆分时,为什么额外的导入会出现在我的条目块中?"。将此选项设置为 false
将禁用此行为。使用 output.preserveModules
选项时,此选项将被忽略,因为在此处,导入永远不会提升。
output.inlineDynamicImports
类型 | 布尔值 |
---|---|
CLI | --inlineDynamicImports /--no-inlineDynamicImports |
默认 | false |
这将内联动态导入,而不是创建新块来创建一个单一包。仅在提供单个输入时才可能。请注意,这将更改执行顺序:如果动态导入被内联,则仅动态导入的模块将立即执行。
output.interop
类型 | "compat" | "auto"| "esModule"| "default"| "defaultOnly"| ((id: string) => "compat"| "auto"| "esModule"| "default"| "defaultOnly") |
---|---|
CLI | --interop <value> |
默认 | "default" |
控制 Rollup 如何处理来自外部依赖项的默认、命名空间和动态导入,这些依赖项采用 CommonJS 等格式,而这些格式本身不支持这些概念。请注意,“default”的默认模式模拟 NodeJS 行为,并且不同于 TypeScript esModuleInterop
。若要获取 TypeScript 的行为,请明确将值设置为 “auto”
。在示例中,我们将使用 CommonJS 格式,但互操作性的选择同样适用于 AMD、IIFE 和 UMD 目标。
为了理解不同的值,假设我们正在为 cjs
目标捆绑以下代码
import ext_default, * as external from 'external1';
console.log(ext_default, external.bar, external);
import('external2').then(console.log);
请记住,对于 Rollup,import * as ext_namespace from 'external'; console.log(ext_namespace.bar);
完全等同于 import {bar} from 'external'; console.log(bar);
,并且将生成相同的代码。然而,在上面的示例中,命名空间对象本身也会传递给全局函数,这意味着我们需要它作为正确形成的对象。
“default”
假设所需值应视为导入模块的默认导出,就像从 NodeJS 中的 ES 模块上下文中导入 CommonJS 一样。还支持命名导入,这些导入被视为默认导入的属性。为了创建命名空间对象,Rollup 注入这些帮助程序jsvar external = require('external1'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty( n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } } ); } }); } n.default = e; return Object.freeze(n); } var external__namespace = /*#__PURE__*/ _interopNamespaceDefault(external); console.log(external, external__namespace.bar, external__namespace); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespaceDefault(require('external2')); }) .then(console.log);
“esModule”
假设所需模块是已转换的 ES 模块,其中所需值对应于模块命名空间,而默认导出是导出对象的.default
属性。这是唯一不会注入任何帮助程序函数的互操作类型jsvar external = require('external1'); console.log(external.default, external.bar, external); Promise.resolve() .then(function () { return require('external2'); }) .then(console.log);
当使用
esModule
时,Rollup 不添加任何额外的互操作帮助程序,并且还支持默认导出的实时绑定。“auto”
通过注入包含代码的帮助程序来组合“esModule”
和“default”
,该代码在运行时检测所需值是否包含__esModule
属性。添加此属性是 TypeScriptesModuleInterop
、Babel 和其他工具实现的一个技巧,用于表示所需值是已转换 ES 模块的命名空间。jsvar external = require('external1'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty( n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } } ); } }); } n.default = e; return Object.freeze(n); } var external__namespace = /*#__PURE__*/ _interopNamespace(external); console.log( external__namespace.default, external__namespace.bar, external__namespace ); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespace(require('external2')); }) .then(console.log);
注意 Rollup 如何重复使用已创建的命名空间对象来获取
default
导出。如果不需要命名空间对象,Rollup 将使用一个更简单的帮助器js// input import ext_default from 'external'; console.log(ext_default); // output var ext_default = require('external'); function _interopDefault(e) { return e && e.__esModule ? e : { default: e }; } var ext_default__default = /*#__PURE__*/ _interopDefault(ext_default); console.log(ext_default__default.default);
compat
等同于"auto"
,只是它为默认导出使用了一个稍有不同的帮助器,该帮助器检查是否存在default
属性,而不是__esModule
属性。除了在 CommonJS 模块导出一个不应为默认导出的属性"default"
的罕见情况下,这通常有助于使互操作“正常工作”,因为它不依赖于特殊的技巧,而是使用鸭子类型jsvar external = require('external1'); function _interopNamespaceCompat(e) { if (e && typeof e === 'object' && 'default' in e) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty( n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } } ); } }); } n.default = e; return Object.freeze(n); } var external__namespace = /*#__PURE__*/ _interopNamespaceCompat(external); console.log( external__namespace.default, external__namespace.bar, external__namespace ); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespaceCompat(require('external2')); }) .then(console.log);
与
"auto"
类似,如果不需要命名空间,Rollup 将使用一个更简单的帮助器js// input import ext_default from 'external'; console.log(ext_default); // output var ext_default = require('external'); function _interopDefaultCompat(e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } var ext_default__default = /*#__PURE__*/ _interopDefaultCompat(ext_default); console.log(ext_default__default.default);
"defaultOnly"
类似于"default"
,但有以下例外- 禁止命名导入。如果遇到这样的导入,即使在
es
和system
格式中,Rollup 也会抛出一个错误。这样可以确保代码的es
版本能够正确导入 Node 中的非内置 CommonJS 模块。 - 虽然命名空间重新导出
export * from 'external';
不被禁止,但它们会被忽略,并且会使 Rollup 显示警告,因为如果没有命名导出,它们将不起作用。 - 当生成命名空间对象时,Rollup 使用一个更简单的帮助器。
以下是 Rollup 将从示例代码创建的内容。请注意,我们从代码中删除了
external.bar
,否则 Rollup 会抛出一个错误,因为如前所述,这等同于一个命名导入。jsvar ext_default = require('external1'); function _interopNamespaceDefaultOnly(e) { return Object.freeze({ __proto__: null, default: e }); } var ext_default__namespace = /*#__PURE__*/ _interopNamespaceDefaultOnly(ext_default); console.log(ext_default, ext_default__namespace); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespaceDefaultOnly( require('external2') ); }) .then(console.log);
- 禁止命名导入。如果遇到这样的导入,即使在
当提供一个函数时,Rollup 会将每个外部 ID 传递给此函数一次,以控制每个依赖项的互操作类型。
例如,如果所有依赖项都是 CommonJs,则以下配置将确保仅允许从 Node 内置项进行命名导入
js// rollup.config.js import builtins from 'builtins'; const nodeBuiltins = new Set(builtins()); export default { // ... output: { // ... interop(id) { if (nodeBuiltins.has(id)) { return 'default'; } return 'defaultOnly'; } } };
还有一些其他选项会影响生成的互操作代码
- 将
output.externalLiveBindings
设置为false
将生成简化的命名空间帮助器以及提取的默认导入的简化代码。 - 将
output.freeze
设置为false
将阻止生成的互操作命名空间对象被冻结。
output.intro/output.outro
类型 | string | ((chunk: ChunkInfo) => string| Promise<string>) |
---|---|
CLI | --intro /--outro <text> |
类似于 output.banner/output.footer
,除了代码转到任何特定于格式的包装器内部。
export default {
//...,
output: {
//...,
intro: 'const ENVIRONMENT = "production";'
}
};
output.manualChunks
类型 | { [chunkAlias: string]: string[] } | ((id: string, {getModuleInfo, getModuleIds}) => string | void) |
---|
允许创建自定义共享公共块。使用对象形式时,每个属性都表示一个块,其中包含列出的模块及其所有依赖项(如果它们是模块图的一部分),除非它们已经位于另一个手动块中。块的名称将由属性键确定。
请注意,列出的模块本身不必是模块图的一部分,如果你正在使用 @rollup/plugin-node-resolve
并且使用包的深度导入,这将很有用。例如
({
manualChunks: {
lodash: ['lodash']
}
});
即使你仅使用 import get from 'lodash/get'
形式的导入,也会将所有 lodash 模块放入手动块中。
使用函数形式时,每个已解析的模块 ID 将传递给函数。如果返回一个字符串,则模块及其所有依赖项将被添加到具有给定名称的手动块中。例如,这将创建一个 vendor
块,其中包含 node_modules
中的所有依赖项
function manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor';
}
}
请注意,如果在实际使用相应模块之前触发了副作用,则手动块可能会改变应用程序的行为。
使用函数形式时,manualChunks
将被传递一个对象作为第二个参数,其中包含函数 getModuleInfo
和 getModuleIds
,它们的工作方式与插件上下文中 this.getModuleInfo
和 this.getModuleIds
的工作方式相同。
这可用于根据模块在模块图中的位置动态确定模块应放入哪个手动块中。例如,考虑一个场景,其中你有一组组件,每个组件都动态导入一组翻译字符串,即
// Inside the "foo" component
function getTranslatedStrings(currentLanguage) {
switch (currentLanguage) {
case 'en':
return import('./foo.strings.en.js');
case 'de':
return import('./foo.strings.de.js');
// ...
}
}
如果大量此类组件一起使用,这将导致大量非常小的块的动态导入:即使我们知道由同一个块导入的同一语言的所有语言文件将始终一起使用,Rollup 也没有此信息。
以下代码将合并仅由单个入口点使用的同一语言的所有文件
function manualChunks(id, { getModuleInfo }) {
const match = /.*\.strings\.(\w+)\.js/.exec(id);
if (match) {
const language = match[1]; // e.g. "en"
const dependentEntryPoints = [];
// we use a Set here so we handle each module at most once. This
// prevents infinite loops in case of circular dependencies
const idsToHandle = new Set(getModuleInfo(id).dynamicImporters);
for (const moduleId of idsToHandle) {
const { isEntry, dynamicImporters, importers } =
getModuleInfo(moduleId);
if (isEntry || dynamicImporters.length > 0)
dependentEntryPoints.push(moduleId);
// The Set iterator is intelligent enough to iterate over
// elements that are added during iteration
for (const importerId of importers) idsToHandle.add(importerId);
}
// If there is a unique entry, we put it into a chunk based on the
// entry name
if (dependentEntryPoints.length === 1) {
return `${
dependentEntryPoints[0].split('/').slice(-1)[0].split('.')[0]
}.strings.${language}`;
}
// For multiple entries, we put it into a "shared" chunk
if (dependentEntryPoints.length > 1) {
return `shared.strings.${language}`;
}
}
}
output.minifyInternalExports
类型 | 布尔值 |
---|---|
CLI | --minifyInternalExports /--no-minifyInternalExports |
默认 | 对于格式 es 和 system 为 true ,或者如果 output.compact 为 true ,否则为 false |
默认情况下,对于格式 es
和 system
,或者如果 output.compact
为 true
,Rollup 将尝试将内部变量导出为单个字母变量,以允许更好地缩小。
示例
输入
// main.js
import './lib.js';
// lib.js
import('./dynamic.js');
export const importantValue = 42;
// dynamic.js
import { importantValue } from './lib.js';
console.log(importantValue);
输出,其中 output.minifyInternalExports: true
// main.js
import './main-5532def0.js';
// main-5532def0.js
import('./dynamic-402de2f0.js');
const importantValue = 42;
export { importantValue as i };
// dynamic-402de2f0.js
import { i as importantValue } from './main-5532def0.js';
console.log(importantValue);
输出,其中 output.minifyInternalExports: false
// main.js
import './main-5532def0.js';
// main-5532def0.js
import('./dynamic-402de2f0.js');
const importantValue = 42;
export { importantValue };
// dynamic-402de2f0.js
import { importantValue } from './main-5532def0.js';
console.log(importantValue);
即使看起来将此选项设置为 true
会使输出更大,但如果使用缩小器,它实际上会使输出更小。在这种情况下,export { importantValue as i }
可以变为例如 export{a as i}
甚至 export{i}
,而否则它会生成 export{ a as importantValue }
,因为缩小器通常不会更改导出签名。
output.paths
类型 | { [id: string]: string } | ((id: string) => string) |
---|
将外部模块 ID 映射到路径。外部 ID 是 无法解析 的 ID 或 external
选项明确提供的 ID。output.paths
提供的路径将用于生成的包中,而不是模块 ID,例如,允许你从 CDN 加载依赖项
// app.js
import { selectAll } from 'd3';
selectAll('p').style('color', 'purple');
// ...
// rollup.config.js
export default {
input: 'app.js',
external: ['d3'],
output: {
file: 'bundle.js',
format: 'amd',
paths: {
d3: 'https://d3.npmjs.net.cn/d3.v4.min'
}
}
};
// bundle.js
define(['https://d3.npmjs.net.cn/d3.v4.min'], function (d3) {
d3.selectAll('p').style('color', 'purple');
// ...
});
output.preserveModules
类型 | 布尔值 |
---|---|
CLI | --preserveModules /--no-preserveModules |
默认 | false |
这种模式不会尽可能地创建尽可能少的块,而是会使用原始模块名称作为文件名,为所有模块创建单独的块。需要 output.dir
选项。仍然会应用摇树,抑制未被提供的入口点使用的文件或在执行时没有副作用的文件,并删除不是入口点的文件的未使用导出。另一方面,如果插件(如 @rollup/plugin-commonjs
)发出其他“虚拟”文件以实现某些结果,则这些文件将使用模式 _virtual/fileName.js
作为实际文件发出。
因此,如果您希望直接从这些文件导入,则不建议盲目地使用此选项将整个文件结构转换为另一种格式,因为可能缺少预期的导出。在这种情况下,您应该通过将所有文件显式指定为入口点(通过将它们添加到 input
选项对象 中)来指定,请参阅其中的示例以了解如何执行此操作。
请注意,在转换为 cjs
或 amd
格式时,默认情况下每个文件都将被视为入口点,且 output.exports
设置为 auto
。这意味着,例如对于 cjs
,仅包含默认导出的文件将被渲染为
// input main.js
export default 42;
// output main.js
('use strict');
var main = 42;
module.exports = main;
将值直接分配给 module.exports
。如果有人导入此文件,他们将通过以下方式访问默认导出
const main = require('./main.js');
console.log(main); // 42
与常规入口点一样,混合默认导出和命名导出的文件将产生警告。您可以通过 output.exports: "named"
强制所有文件使用命名导出模式来避免警告。在这种情况下,需要通过导出的 .default
属性访问默认导出
// input main.js
export default 42;
// output main.js
('use strict');
Object.defineProperty(exports, '__esModule', { value: true });
var main = 42;
exports.default = main;
// consuming file
const main = require('./main.js');
console.log(main.default); // 42
output.preserveModulesRoot
类型 | string |
---|---|
CLI | --preserveModulesRoot <directory-name> |
在 output.preserveModules
为 true
时,应从 output.dir
路径中删除的输入模块的目录路径。
例如,给定以下配置
export default {
input: ['src/module.js', `src/another/module.js`],
output: [
{
format: 'es',
dir: 'dist',
preserveModules: true,
preserveModulesRoot: 'src'
}
]
};
preserveModulesRoot
设置确保输入模块将输出到路径 dist/module.js
和 dist/another/module.js
。
此选项在使用插件(例如 @rollup/plugin-node-resolve
)时特别有用,该插件可能会导致输出目录结构发生变化。这可能会发生在未将第三方模块标记为 external
的情况下,或者在开发依赖于彼此且未标记为 external
的多个包的单一存储库中时。
output.sourcemap
类型 | 布尔值 | 'inline'| 'hidden' |
---|---|
CLI | -m /--sourcemap /--no-sourcemap |
默认 | false |
如果为 true
,则将创建单独的 sourcemap 文件。如果为 "inline"
,则将 sourcemap 附加到结果 output
文件中,作为数据 URI。"hidden"
的工作方式与 true
相同,但会禁止捆绑文件中相应的 sourcemap 注释。
output.sourcemapBaseUrl
类型 | string |
---|---|
CLI | --sourcemapBaseUrl <url> |
默认情况下,Rollup 生成的 sourcemap 文件使用相对 URL 来引用它们描述的文件。通过提供绝对基本 URL,例如 https://example.com
,sourcemap 将改用绝对 URL。
output.sourcemapExcludeSources
类型 | 布尔值 |
---|---|
CLI | --sourcemapExcludeSources /--no-sourcemapExcludeSources |
默认 | false |
如果为 true
,则不会将源的实际代码添加到 sourcemap 中,从而使它们变得小得多。
output.sourcemapFile
类型 | string |
---|---|
CLI | --sourcemapFile <file-name-with-path> |
生成包的位置。如果这是绝对路径,则 sourcemap 中的所有 sources
路径都将相对于该路径。map.file
属性是 sourcemapFile
的基本名称,因为 sourcemap 的位置被认为与包相邻。
如果指定了 output
,则不需要 sourcemapFile
,在这种情况下,将通过向包的输出文件名添加 “.map” 来推断输出文件名。
output.sourcemapFileNames
类型 | string | ((chunkInfo: ChunkInfo) => string) |
---|---|
CLI | --sourcemapFileNames <pattern> |
用于 sourcemap 的模式,或一个函数,该函数针对每个 sourcemap 调用以返回这样的模式。模式支持以下占位符
[format]
:输出选项中定义的渲染格式,例如es
或cjs
。[hash]
:仅基于最终生成的 sourcemap 内容的哈希。您还可以通过例如[hash:10]
设置特定的哈希长度。默认情况下,它将创建一个 base-64 哈希。如果您需要减少字符集,请参阅output.hashCharacters
[chunkhash]
:与用于相应生成块(如果存在)的哈希相同。[name]
:入口点的文件名(无扩展名),除非使用输入的对象形式定义了不同的名称。
正斜杠 /
可用于将文件放置在子目录中。使用函数时,chunkInfo
是 generateBundle
中的一个精简版本,不包含依赖于文件名且不包含有关已渲染模块的信息的属性,因为渲染仅在生成文件名后才会发生。但是,你可以访问包含的 moduleIds
列表。另请参阅 output.assetFileNames
、output.chunkFileNames
。
output.sourcemapIgnoreList
类型 | 布尔值 | (relativeSourcePath: 字符串, sourcemapPath: 字符串) => 布尔值 |
---|
一个谓词,用于决定是否忽略源映射中的源文件,用于填充 x_google_ignoreList
源映射扩展。relativeSourcePath
是从生成的 .map
文件到相应源文件的相对路径,而 sourcemapPath
是生成的源映射文件的完全解析路径。
import path from 'node:path';
export default {
input: 'src/main',
output: [
{
file: 'bundle.js',
sourcemapIgnoreList: (relativeSourcePath, sourcemapPath) => {
// will ignore-list all files with node_modules in their paths
return relativeSourcePath.includes('node_modules');
},
format: 'es',
sourcemap: true
}
]
};
当您未明确指定此选项时,默认情况下,它会将路径中带有 node_modules
的所有文件放入忽略列表中。您可以在此处指定 false
以完全关闭忽略列表。
output.sourcemapPathTransform
类型 | (relativeSourcePath: 字符串, sourcemapPath: 字符串) => 字符串 |
---|
应用于源映射中每个路径的转换。relativeSourcePath
是从生成的 .map
文件到相应源文件的相对路径,而 sourcemapPath
是生成的源映射文件的完全解析路径。
import path from 'node:path';
export default {
input: 'src/main',
output: [
{
file: 'bundle.js',
sourcemapPathTransform: (relativeSourcePath, sourcemapPath) => {
// will replace relative paths with absolute paths
return path.resolve(
path.dirname(sourcemapPath),
relativeSourcePath
);
},
format: 'es',
sourcemap: true
}
]
};
output.validate
类型 | 布尔值 |
---|---|
CLI | --validate /--no-validate |
默认 | false |
重新解析每个生成的块,以检测生成的代码是否为有效的 JavaScript。这对于调试使用 renderChunk
钩子转换代码的插件生成的输出非常有用。
如果代码无效,将会发出警告。请注意,不会抛出任何错误,因此您仍然可以检查生成的输出。要将此警告提升为错误,您可以在 onwarn
处理程序中对其进行监视。
preserveEntrySignatures
类型 | "strict" | "allow-extension" | "exports-only"| false |
---|---|
CLI | --preserveEntrySignatures <strict | allow-extension> /--no-preserveEntrySignatures |
默认 | "exports-only" |
控制 Rollup 是否尝试确保入口块具有与底层入口模块相同的导出。
- 如果设置为
"strict"
,则 Rollup 将在入口块中创建与相应入口模块中完全相同的导出。如果由于需要将其他内部导出添加到块中而无法实现此目的,则 Rollup 将创建一个“外观”入口块,该块仅从其他块重新导出必要的绑定,但本身不包含任何代码。这是库的推荐设置。 “allow-extension”
将在入口块中创建入口模块的所有导出,但必要时也可能会添加其他导出,避免“门面”入口块。此设置对于不需要严格签名的库来说有意义。- 如果入口模块有导出,
“exports-only”
的行为类似于“strict”
,否则其行为类似于“allow-extension”
。 false
不会将入口模块的任何导出添加到对应的块,并且甚至不会包含对应的代码,除非这些导出在包的其它地方使用。但是,内部导出可能会添加到入口块。对于将入口块放在脚本标签中的 Web 应用程序,这是推荐的设置,因为它可能会减少块的数量和包的大小。
示例
输入
// main.js
import { shared } from './lib.js';
export const value = `value: ${shared}`;
import('./dynamic.js');
// lib.js
export const shared = 'shared';
// dynamic.js
import { shared } from './lib.js';
console.log(shared);
preserveEntrySignatures: "strict"
的输出
// main.js
export { v as value } from './main-50a71bb6.js';
// main-50a71bb6.js
const shared = 'shared';
const value = `value: ${shared}`;
import('./dynamic-cd23645f.js');
export { shared as s, value as v };
// dynamic-cd23645f.js
import { s as shared } from './main-50a71bb6.js';
console.log(shared);
preserveEntrySignatures: "allow-extension"
的输出
// main.js
const shared = 'shared';
const value = `value: ${shared}`;
import('./dynamic-298476ec.js');
export { shared as s, value };
// dynamic-298476ec.js
import { s as shared } from './main.js';
console.log(shared);
preserveEntrySignatures: false
的输出
// main.js
import('./dynamic-39821cef.js');
// dynamic-39821cef.js
const shared = 'shared';
console.log(shared);
目前,覆盖单个入口块此设置的唯一方法是使用插件 API 并通过 this.emitFile
发射这些块,而不是使用 input
选项。
strictDeprecations
类型 | 布尔值 |
---|---|
CLI | --strictDeprecations /--no-strictDeprecations |
默认 | false |
启用此标志时,Rollup 将在使用弃用功能时抛出错误,而不是显示警告。此外,标记为在下一个主要版本中接收弃用警告的功能在使用时也将抛出错误。
此标志旨在供插件作者等使用,以便他们能够尽早调整其插件以适应即将到来的主要版本。
危险区域
除非您知道自己在做什么,否则可能不需要使用这些选项!
context
类型 | string |
---|---|
CLI | --context <contextVariable> |
默认 | undefined |
默认情况下,模块的上下文(即顶层的 this
的值)为 undefined
。在极少数情况下,您可能需要将其更改为其他内容,例如 'window'
。
moduleContext
类型 | ((id: string) => string) | { [id: string]: string } |
---|
与 context
相同,但按模块设置 – 可以是 id: context
对的对象,也可以是 id => context
函数。
output.amd
类型 | { id?: string, autoId?: boolean, basePath?: string, define?: string } |
---|
请注意,id
只能用于单文件构建,且不能与 autoId
/basePath
结合使用。
output.amd.id
类型 | string |
---|---|
CLI | --amd.id <amdId> |
用于 AMD/UMD 捆绑包的 ID
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
id: 'my-bundle'
}
};
// -> define('my-bundle', ['dependency'], ...
output.amd.autoId
类型 | 布尔值 |
---|---|
CLI | --amd.autoId |
将 ID 设置为块 ID(删除了 '.js' 扩展名)。
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
autoId: true
}
};
// -> define('main', ['dependency'], ...
// -> define('dynamic-chunk', ['dependency'], ...
output.amd.basePath
类型 | string |
---|---|
CLI | --amd.basePath |
将预先添加到自动生成 ID 的路径。如果构建将放置在另一个 AMD 项目中,且不在根目录中,则此选项非常有用。
仅与 output.amd.autoId
有效。
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
autoId: true,
basePath: 'some/where'
}
};
// -> define('some/where/main', ['dependency'], ...
// -> define('some/where/dynamic-chunk', ['dependency'], ...
output.amd.define
类型 | string |
---|---|
CLI | --amd.define <defineFunctionName> |
要使用的函数名称,而不是 define
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
define: 'def'
}
};
// -> def(['dependency'],...
output.amd.forceJsExtensionForImports
类型 | 布尔值 |
---|---|
CLI | --amd.forceJsExtensionForImports |
默认 | false |
为生成的块和本地 AMD 模块的导入添加 .js
扩展名
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
forceJsExtensionForImports: true
}
};
// -> define(['./chunk-or-local-file.js', 'dependency', 'third/dependency'],...
output.esModule
类型 | 布尔值 | "if-default-prop" |
---|---|
CLI | --esModule /--no-esModule |
默认 | "if-default-prop" |
在为非 ES 格式生成导出时,是否添加 __esModule: true
属性。此属性表示导出的值是 ES 模块的命名空间,并且此模块的默认导出对应于导出对象的 .default
属性。
- 在使用 命名导出模式 时,
true
始终会添加此属性,这与其他工具类似。 "if-default-prop"
仅在使用命名导出模式且存在默认导出时才添加属性。细微差别在于,如果没有默认导出,库的 CommonJS 版本的使用者将获得所有命名导出作为默认导出,而不是错误或undefined
。我们选择将其设为默认值,因为__esModule
属性不是任何 JavaScript 运行时遵循的标准,并且会导致许多互操作问题,因此我们希望将其使用限制在真正需要的情况下。- 另一方面,
false
永远不会添加属性,即使默认导出将成为属性.default
。
另请参阅 output.interop
。
output.exports
类型 | "auto" | "default"| "named"| "none" |
---|---|
CLI | --exports <exportMode> |
默认 | 'auto' |
要使用的导出模式。默认为 auto
,它根据 input
模块导出的内容猜测你的意图
default
– 如果你仅使用export default ...
导出一个内容;请注意,当生成旨在与 ESM 输出互换的 CommonJS 输出时,这可能会导致问题,请参见下文named
– 如果你使用命名导出none
– 如果你不导出任何内容(例如,你正在构建一个应用程序,而不是一个库)
由于这仅是输出转换,因此你只能在默认导出是所有入口块的唯一导出时选择 default
。同样,你只能在没有导出时选择 none
,否则 Rollup 将抛出错误。
default
和 named
之间的区别会影响其他人使用你的包的方式。如果你使用 default
,CommonJS 用户可以执行此操作,例如
// your-lib package entry
export default 'Hello world';
// a CommonJS consumer
/* require( "your-lib" ) returns "Hello World" */
const hello = require('your-lib');
使用 named
,用户会执行此操作
// your-lib package entry
export const hello = 'Hello world';
// a CommonJS consumer
/* require( "your-lib" ) returns {hello: "Hello World"} */
const hello = require('your-lib').hello;
/* or using destructuring */
const { hello } = require('your-lib');
问题在于,如果你使用 named
导出但也有 default
导出,用户将必须执行类似这样的操作来使用默认导出
// your-lib package entry
export default 'foo';
export const bar = 'bar';
// a CommonJS consumer
/* require( "your-lib" ) returns {default: "foo", bar: "bar"} */
const foo = require('your-lib').default;
const bar = require('your-lib').bar;
/* or using destructuring */
const { default: foo, bar } = require('your-lib');
注意:有一些工具(例如 Babel、TypeScript、Webpack 和 @rollup/plugin-commonjs
)能够使用 ES 模块解析 CommonJS require(...)
调用。如果你要生成的 CommonJS 输出旨在与这些工具的 ESM 输出互换,则你应始终使用 named
导出模式。原因是,大多数此类工具在 require
上默认返回 ES 模块的命名空间,其中默认导出是 .default
属性。
换句话说,对于这些工具,你无法创建包接口,其中 const lib = require("your-lib")
产生与 import lib from "your-lib"
相同的结果。但是,使用命名导出模式,const {lib} = require("your-lib")
将等效于 import {lib} from "your-lib"
。
output.externalLiveBindings
类型 | 布尔值 |
---|---|
CLI | --externalLiveBindings /--no-externalLiveBindings |
默认 | true |
当设置为 false
时,Rollup 不会生成代码来支持外部导入的实时绑定,而是假设导出不会随时间而改变。这将使 Rollup 能够生成更优化的代码。请注意,当涉及外部依赖关系的循环依赖时,这可能会导致问题。
这将避免 Rollup 在代码中生成 getter 的大多数情况,因此在许多情况下可用于使代码与 IE8 兼容。
示例
// input
export { x } from 'external';
// CJS output with externalLiveBindings: true
var external = require('external');
Object.defineProperty(exports, 'x', {
enumerable: true,
get: function () {
return external.x;
}
});
// CJS output with externalLiveBindings: false
var external = require('external');
exports.x = external.x;
output.freeze
类型 | 布尔值 |
---|---|
CLI | --freeze /--no-freeze |
默认 | true |
是否对动态访问的命名空间导入对象(即 import * as namespaceImportObject from...
)执行 Object.freeze()
。
output.indent
类型 | 布尔值 | 字符串 |
---|---|
CLI | --indent /--no-indent |
默认 | true |
要使用的缩进字符串,适用于需要缩进代码的格式(amd
、iife
、umd
、system
)。还可以是 false
(不缩进)或 true
(默认值 - 自动缩进)
// rollup.config.js
export default {
...,
output: {
...,
indent: false
}
};
output.noConflict
类型 | 布尔值 |
---|---|
CLI | --noConflict /--no-noConflict |
默认 | false |
这将在 UMD 捆绑包中生成一个额外的 noConflict
导出。在 IIFE 场景中调用时,此方法将返回捆绑包导出,同时将相应的全局变量恢复为其先前值。
output.reexportProtoFromExternal
类型 | 布尔值 |
---|---|
CLI | --reexportProtoFromExternal /--no-reexportProtoFromExternal |
默认 | true |
此选项仅在 output.format
设置为 ['amd', 'cjs', 'iife', 'umd']
之一且 output.externalLiveBindings
设置为 false 时才有效。
为了最大程度的兼容性,Rollup 默认从外部模块重新导出 __proto__
。但是,对于常见用例,强烈建议将此值设置为 false,因为它可以有效减小输出大小。
// the input file
export * from 'rollup';
// the output file if the output.format is cjs
'use strict';
// reexportProtoFromExternal is true
var rollup = require('rollup');
Object.prototype.hasOwnProperty.call(rollup, '__proto__') &&
!Object.prototype.hasOwnProperty.call(exports, '__proto__') &&
Object.defineProperty(exports, '__proto__', {
enumerable: true,
value: rollup['__proto__']
});
Object.keys(rollup).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
exports[k] = rollup[k];
});
// reexportProtoFromExternal is false
var rollup = require('rollup');
Object.keys(rollup).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
exports[k] = rollup[k];
});
output.sanitizeFileName
类型 | 布尔值 | (字符串) => 字符串 |
---|---|
CLI | --sanitizeFileName /no-sanitizeFileName |
默认 | true |
设置为 false
以禁用所有块名称清理(删除 \0
、?
和 *
字符)。
或者设置为函数以允许自定义块名称清理。
output.strict
类型 | 布尔值 |
---|---|
CLI | --strict /--no-strict |
默认 | true |
是否在生成的非 ES 捆绑包的顶部包含“use strict”编译指示。严格来说,ES 模块始终处于严格模式,因此您不应该无缘无故地禁用此选项。
output.systemNullSetters
类型 | 布尔值 |
---|---|
CLI | --systemNullSetters /--no-systemNullSetters |
默认 | true |
在输出 system
模块格式时,默认情况下,空 setter 函数将替换为 null
作为输出简化。这与 v6.3.3 之前的 SystemJS 不兼容。停用此选项以输出旧版 SystemJS 支持的空函数。
preserveSymlinks
类型 | 布尔值 |
---|---|
CLI | --preserveSymlinks |
默认 | false |
设置为 false
时,在解析文件时将遵循符号链接。设置为 true
时,符号链接将被视为文件位于链接所在的位置,而不是被遵循。为了说明,考虑以下情况
// /main.js
import { x } from './linked.js';
console.log(x);
// /linked.js
// this is a symbolic link to /nested/file.js
// /nested/file.js
export { x } from './dep.js';
// /dep.js
export const x = 'next to linked';
// /nested/dep.js
export const x = 'next to original';
如果 preserveSymlinks
为 false
,那么从 /main.js
创建的包将记录“next to original”,因为它将使用符号链接文件的位置来解析其依赖项。但是,如果 preserveSymlinks
为 true
,它将记录“next to linked”,因为符号链接将不会被解析。
shimMissingExports
类型 | 布尔值 |
---|---|
CLI | --shimMissingExports /--no-shimMissingExports |
默认 | false |
如果提供了此选项,则从不定义这些绑定的文件导入绑定时,捆绑不会失败。相反,将为这些绑定创建新变量,其值为 undefined
。
treeshake
类型 | 布尔值 | TreeshakingPreset | TreeshakingOptions |
---|---|
CLI | --treeshake /--no-treeshake |
默认 | true |
type TreeshakingPreset = 'smallest' | 'safest' | 'recommended';
interface TreeshakingOptions {
annotations?: boolean;
correctVarValueBeforeDeclaration?: boolean;
moduleSideEffects?: ModuleSideEffectsOption;
preset?: TreeshakingPreset;
propertyReadSideEffects?: boolean | 'always';
tryCatchDeoptimization?: boolean;
unknownGlobalSideEffects?: boolean;
}
type ModuleSideEffectsOption =
| boolean
| 'no-external'
| string[]
| HasModuleSideEffects;
type HasModuleSideEffects = (id: string, external: boolean) => boolean;
是否应用摇树优化并微调摇树优化过程。将此选项设为 false
将生成更大的包,但可能会提高构建性能。您还可以选择三个预设之一,如果添加了新选项,这些预设将自动更新
"smallest"
将为您选择选项值,以尽可能地最小化输出大小。只要您不依赖于某些模式,这应该适用于大多数代码库,这些模式当前为- 具有副作用的 getter 仅在使用返回值时才会保留 (
treeshake.propertyReadSideEffects: false
) - 仅当使用至少一个导出值时,才会保留来自导入模块的代码 (
treeshake.moduleSideEffects: false
) - 您不应该捆绑依赖于检测损坏内建函数的多态填充 (
treeshake.tryCatchDeoptimization: false
) - 某些语义问题可能会被忽略 (
treeshake.unknownGlobalSideEffects: false
,treeshake.correctVarValueBeforeDeclaration: false
)
- 具有副作用的 getter 仅在使用返回值时才会保留 (
"recommended"
应该适用于大多数使用模式。不过,某些语义问题可能会被忽略 (treeshake.unknownGlobalSideEffects: false
,treeshake.correctVarValueBeforeDeclaration: false
)"safest"
尝试尽可能符合规范,同时仍然提供一些基本的摇树优化功能。true
等效于不指定选项,并且将始终选择默认值(见下文)。
如果您发现由摇树优化算法导致的错误,请提交问题!将此选项设置为对象意味着启用了摇树优化,并授予以下附加选项
treeshake.annotations
类型 | 布尔值 |
---|---|
CLI | --treeshake.annotations /--no-treeshake.annotations |
默认 | true |
如果为 false
,则忽略注释中的提示
@__PURE__
包含 @__PURE__
或 #__PURE__
的注释将特定的函数调用或构造函数调用标记为无副作用。这意味着 Rollup 将进行树摇晃,即删除调用,除非返回值在未进行树摇晃的某些代码中使用。这些注释需要紧接在调用调用之前才能生效。以下代码将完全进行树摇晃,除非此选项设置为 false
,在这种情况下,它将保持不变。
/*@__PURE__*/ console.log('side-effect');
class Impure {
constructor() {
console.log('side-effect');
}
}
/*@__PURE__ There may be additional text in the comment */ new Impure();
如果此类注释直接位于函数调用或构造函数调用之前,并且仅通过空格或注释与被调用方分隔,则此类注释被视为有效。唯一的例外是括号,它会将调用或调用括起来。
无效的注释将被删除,并且 Rollup 将发出警告。有效的注释将保留在代码中,除非其函数调用或构造函数调用也被删除。
@__NO_SIDE_EFFECTS__
包含 @__NO_SIDE_EFFECTS__
或 #__NO_SIDE_EFFECTS__
的注释将函数声明本身标记为无副作用。将函数标记为无副作用后,对该函数的所有调用都将被视为无副作用。以下代码将完全进行树摇晃,除非此选项设置为 false
,在这种情况下,它将保持不变。
/*@__NO_SIDE_EFFECTS__*/
function impure() {
console.log('side-effect');
}
/*@__NO_SIDE_EFFECTS__*/
const impureArrowFn = () => {
console.log('side-effect');
};
impure(); // <-- call will be considered as side effect free
impureArrowFn(); // <-- call will be considered as side effect free
如果此类注释直接位于函数声明或常量变量声明之前,并且仅通过空格或注释与声明分隔,则此类注释被视为有效。
无效的注释将被删除,并且 Rollup 将发出警告。有效的注释将保留在代码中,除非其声明也被删除。
treeshake.correctVarValueBeforeDeclaration
类型 | 布尔值 |
---|---|
CLI | --treeshake.correctVarValueBeforeDeclaration /--no-treeshake.correctVarValueBeforeDeclaration |
默认 | false |
在某些极端情况下,如果在变量声明赋值之前访问变量并且未重新赋值,则 Rollup 可能会错误地假设变量在整个程序中都是常量,如下面的示例所示。但是,如果使用 var
声明变量,则不是这种情况,因为可以在声明之前访问这些变量,在声明之前它们将计算为 undefined
。选择 true
将确保 Rollup 不会对使用 var
声明的变量的值做出任何假设。但请注意,这可能会对树摇晃结果产生明显的负面影响。
// everything will be tree-shaken unless treeshake.correctVarValueBeforeDeclaration === true
let logBeforeDeclaration = false;
function logIfEnabled() {
if (logBeforeDeclaration) {
log();
}
var value = true;
function log() {
if (!value) {
console.log('should be retained, value is undefined');
}
}
}
logIfEnabled(); // could be removed
logBeforeDeclaration = true;
logIfEnabled(); // needs to be retained as it displays a log
treeshake.manualPureFunctions
类型 | string[] |
---|---|
CLI | --treeshake.manualPureFunctions <names> |
允许手动定义一个函数名称列表,这些函数名称应始终被视为“纯函数”,即在调用时不会产生副作用,例如更改全局状态等。检查仅按名称执行。
这不仅有助于删除死代码,还可以改善 JavaScript 块生成,尤其是在使用 output.experimentalMinChunkSize
时。
除了与该名称匹配的任何函数外,纯函数上的任何属性和从纯函数返回的任何函数也将被视为纯函数,并且不会检查访问任何属性是否会产生副作用。
// rollup.config.js
export default {
treeshake: {
preset: 'smallest',
manualPureFunctions: ['styled', 'local']
}
// ...
};
// code
import styled from 'styled-components';
const local = console.log;
local(); // removed
styled.div`
color: blue;
`; // removed
styled?.div(); // removed
styled()(); // removed
styled().div(); // removed
treeshake.moduleSideEffects
类型 | boolean| "no-external"| string[]| (id: string, external: boolean) => boolean |
---|---|
CLI | --treeshake.moduleSideEffects /--no-treeshake.moduleSideEffects /--treeshake.moduleSideEffects no-external |
默认 | true |
如果为 false
,则假设模块和未从中导入任何内容的外部依赖项没有其他副作用,例如在不检查的情况下改变全局变量或记录。对于外部依赖项,这将抑制空导入
// input file
import { unused } from 'external-a';
import 'external-b';
console.log(42);
// output with treeshake.moduleSideEffects === true
import 'external-a';
import 'external-b';
console.log(42);
// output with treeshake.moduleSideEffects === false
console.log(42);
对于非外部模块,false
将不会包含来自模块的任何语句,除非包含了来自该模块的至少一个导入
// input file a.js
import { unused } from './b.js';
console.log(42);
// input file b.js
console.log('side-effect');
const ignored = 'will still be removed';
// output with treeshake.moduleSideEffects === true
console.log('side-effect');
console.log(42);
// output with treeshake.moduleSideEffects === false
console.log(42);
您还可以提供一个具有副作用的模块列表或一个函数来分别确定每个模块的副作用。值 "no-external"
仅在可能的情况下删除外部导入,并且等效于函数 (id, external) => !external
;
如果将此标志设置为 false
的模块从另一个模块重新导出一个变量,并且使用了此变量,则是否扫描重新导出模块以查找副作用取决于如何重新导出该变量
// input file a.js
import { foo } from './b.js';
console.log(foo);
// input file b.js
// direct reexports will ignore side effects
export { foo } from './c.js';
console.log('this side-effect is ignored');
// input file c.js
// indirect reexports will include side effects
import { foo } from './d.js';
foo.mutated = true;
console.log('this side-effect and the mutation are retained');
export { foo };
// input file d.js
export const foo = 42;
// output with treeshake.moduleSideEffects === false
const foo = 42;
foo.mutated = true;
console.log('this side-effect and the mutation are retained');
console.log(foo);
请注意,尽管有此名称,但此选项不会向没有副作用的模块“添加”副作用。如果出于依赖项跟踪的需要,某个空模块“包含”在捆绑包中很重要,则插件接口允许您通过 resolveId
、load
或 transform
钩子将模块指定为从摇树中排除。
treeshake.preset
类型 | "smallest" | "safest"| "recommended" |
---|---|
CLI | --treeshake <value> |
允许在覆盖某些选项的同时选择上面列出的预设之一。
export default {
treeshake: {
preset: 'smallest',
propertyReadSideEffects: true
}
// ...
};
treeshake.propertyReadSideEffects
类型 | boolean| 'always' |
---|---|
CLI | --treeshake.propertyReadSideEffects /--no-treeshake.propertyReadSideEffects |
默认 | true |
如果为 true
,则保留 Rollup 确定有副作用的未使用的属性读取。这包括访问 null
或 undefined
的属性,或通过属性访问触发显式 getter。请注意,这并不包括对作为函数参数传递的对象进行解构赋值或 getter。
如果为 false
,则假设读取对象的属性永远没有副作用。根据你的代码,禁用此选项可以显著减小 bundle 大小,但如果你依赖 getter 或非法属性访问的错误,则可能会破坏功能。
如果为 'always'
,则假设所有成员属性访问(包括解构)都有副作用。此设置建议用于依赖有副作用的 getter 的代码。它通常会导致较大的 bundle 大小,但比完全禁用 treeshake
小。
// Will be removed if treeshake.propertyReadSideEffects === false
const foo = {
get bar() {
console.log('effect');
return 'bar';
}
};
const result = foo.bar;
const illegalAccess = foo.quux.tooDeep;
treeshake.tryCatchDeoptimization
类型 | 布尔值 |
---|---|
CLI | --treeshake.tryCatchDeoptimization /--no-treeshake.tryCatchDeoptimization |
默认 | true |
默认情况下,Rollup 假设在摇树时运行时的许多内置全局变量都按照最新规范运行,并且不会抛出意外错误。为了支持依赖于抛出这些错误的功能检测工作流,Rollup 默认会在 try 语句中停用摇树。如果从 try 语句中调用函数参数,则该参数也将被取消优化。如果你不需要此功能并且希望在 try 语句中进行摇树,请将 treeshake.tryCatchDeoptimization
设置为 false
。
function otherFn() {
// even though this function is called from a try-statement, the next line
// will be removed as side-effect-free
Object.create(null);
}
function test(callback) {
try {
// calls to otherwise side-effect-free global functions are
// retained inside try-statements for tryCatchDeoptimization: true
Object.create(null);
// calls to other function are retained as well but the body of
// this function may again be subject to tree-shaking
otherFn();
// if a parameter is called, then all arguments passed to that
// function parameter will be deoptimized
callback();
} catch {}
}
test(() => {
// will be ratained
Object.create(null);
});
// call will be retained but again, otherFn is not deoptimized
test(otherFn);
treeshake.unknownGlobalSideEffects
类型 | 布尔值 |
---|---|
CLI | --treeshake.unknownGlobalSideEffects /--no-treeshake.unknownGlobalSideEffects |
默认 | true |
由于访问不存在的全局变量会抛出错误,因此 Rollup 默认保留对非内置全局变量的任何访问。将此选项设置为 false
以避免此检查。对于大多数代码库来说,这可能是安全的。
// input
const jQuery = $;
const requestTimeout = setTimeout;
const element = angular.element;
// output with unknownGlobalSideEffects == true
const jQuery = $;
const element = angular.element;
// output with unknownGlobalSideEffects == false
const element = angular.element;
在示例中,最后一行始终保留,因为访问 element
属性也可能抛出错误,例如,如果 angular
为 null
。要避免此检查,请将 treeshake.propertyReadSideEffects
也设置为 false
。
实验性选项
这些选项反映了尚未完全最终确定的一些新功能。因此,可用性、行为和用法可能会在小版本之间发生变化。
experimentalCacheExpiry
类型 | 数字 |
---|---|
CLI | --experimentalCacheExpiry <numberOfRuns> |
默认 | 10 |
确定插件不再使用的缓存资产在经过多少次运行后应被移除。
experimentalLogSideEffects
类型 | 布尔值 |
---|---|
CLI | --experimentalLogSideEffects /--no-experimentalLogSideEffects |
默认 | false |
设置为 true
时,这会将每个文件中找到的第一个副作用记录到控制台。这对于弄清楚哪些文件有副作用以及实际副作用是什么非常有帮助。移除副作用可以改善摇树和块生成,并且对于使 output.experimentalMinChunkSize
起作用至关重要。
但是,此选项只会记录顶级语句。有时,例如在立即调用的函数表达式的情况下,实际副作用可能隐藏在嵌套表达式中。
output.experimentalMinChunkSize
类型 | 数字 |
---|---|
CLI | --experimentalMinChunkSize <size> |
默认 | 1 |
为代码拆分设置设置最小块大小目标(以字节为单位)。当此值设置为默认值 1
时,Rollup 将尝试将不包含代码(除了导入和重新导出)的块合并到其他块中。仅当合并不会改变加载任何条目时执行的副作用时,才会执行合并。对于值 1
,仅允许合并不会增加任何条目的加载代码量。
较大的值将尝试将低于限制的任何块合并到其他块中。在这种情况下,可以接受条目可能加载一些不必要的代码。不过,该算法始终尝试以最大程度减少不必要代码的方式进行合并。
不幸的是,由于块处理的方式,块大小是在缩小器等任何块渲染插件运行之前测量的,这意味着你应该使用足够高的限制来考虑这一点。但是,在计算大小时,它会考虑顶级语句的摇树。
perf
类型 | 布尔值 |
---|---|
CLI | --perf /--no-perf |
默认 | false |
是否收集性能时间。当从命令行或配置文件中使用时,将显示有关当前捆绑过程的详细测量。当从 JavaScript API 使用时,返回的捆绑对象将包含一个附加的 getTimings()
函数,该函数可在任何时候调用以检索所有累积的测量。
getTimings()
返回以下形式的对象
{
"# BUILD": [ 698.020877, 33979632, 45328080 ],
"## parse modules": [ 537.509342, 16295024, 27660296 ],
"load modules": [ 33.253778999999994, 2277104, 38204152 ],
...
}
对于每个键,第一个数字表示经过的时间,第二个数字表示内存消耗的变化,第三个数字表示此步骤后的总内存消耗。这些步骤的顺序是 Object.keys
使用的顺序。顶级键以 #
开头,并包含嵌套步骤的时间,即在上面的示例中,# BUILD
步骤的 698 毫秒包括 ## parse modules
步骤的 538 毫秒。
监视
类型 | WatcherOptions | false |
---|---|
默认 | {} |
interface WatcherOptions {
buildDelay?: number;
chokidar?: ChokidarOptions;
clearScreen?: boolean;
exclude?: string | RegExp | (string | RegExp)[];
include?: string | RegExp | (string | RegExp)[];
skipWrite?: boolean;
}
指定监视模式的选项或防止此配置被监视。仅当使用配置数组时,指定 false
才真正有用。在这种情况下,此配置在监视模式下不会被构建或重建,但它将在正常运行 Rollup 时被构建
// rollup.config.js
export default [
{
input: 'main.js',
output: { file: 'bundle.cjs.js', format: 'cjs' }
},
{
input: 'main.js',
watch: false,
output: { file: 'bundle.es.js', format: 'es' }
}
];
这些选项仅在使用 --watch
标志运行 Rollup 或使用 rollup.watch
时生效。
watch.buildDelay
类型 | 数字 |
---|---|
CLI | --watch.buildDelay <number> |
默认 | 0 |
配置 Rollup 在触发重建之前将等待进一步更改多长时间(以毫秒为单位)。默认情况下,Rollup 不会等待,但在 chokidar 实例中配置了一个小的去抖动超时。将此值设置为大于 0
的值意味着 Rollup 仅在配置的毫秒数内没有更改时才会触发重建。如果监视了多个配置,Rollup 将使用最大的配置构建延迟。
watch.chokidar
类型 | ChokidarOptions |
---|
将传递给已捆绑 chokidar 实例的监视选项的可选对象。请参阅 chokidar 文档 以了解有哪些选项可用。
watch.clearScreen
类型 | 布尔值 |
---|---|
CLI | --watch.clearScreen /--no-watch.clearScreen |
默认 | true |
在触发重建时是否清除屏幕。
watch.exclude
类型 | string | RegExp| (string| RegExp)[] |
---|---|
CLI | --watch.exclude <files> |
防止监视文件
// rollup.config.js
export default {
...,
watch: {
exclude: 'node_modules/**'
}
};
watch.include
类型 | string | RegExp| (string| RegExp)[] |
---|---|
CLI | --watch.include <files> |
将文件监视限制为某些文件。请注意,这仅过滤模块图,但不允许添加其他监视文件
// rollup.config.js
export default {
...,
watch: {
include: 'src/**'
}
};
watch.skipWrite
类型 | 布尔值 |
---|---|
CLI | --watch.skipWrite /--no-watch.skipWrite |
默认 | false |
在触发重建时是否跳过 bundle.write()
步骤。
已弃用的选项
☢️ 这些选项已被弃用,并可能在未来的 Rollup 版本中被移除。
output.externalImportAssertions
改用 output.externalImportAttributes
选项。
类型 | 布尔值 |
---|---|
CLI | --externalImportAssertions /--no-externalImportAssertions |
默认 | true |
如果输出格式为 es
,则是否在输出中向外部导入添加导入断言。默认情况下,断言从输入文件中获取,但插件稍后可以添加或删除断言。例如,import "foo" assert {type: "json"}
将导致相同的导入出现在输出中,除非该选项设置为 false
。请注意,模块的所有导入都需要具有相符的断言,否则会发出警告。