Skip to content

配置选项

核心功能

external

类型:(string | RegExp)[]| RegExp| string| (id: string, parentId: string, isResolved: boolean) => boolean
命令行接口:-e/--external <external-id,another-external-id,...>

接受 id 并返回 true(外部)或 false(非外部)的函数,或模块 ID 的 Array,或匹配模块 ID 的正则表达式,应保留在打包包外部。 也可以只是单个 ID 或正则表达式。 匹配的 ID 应该是:

Either a function that takes an id and returns true (external) or false (not external), or an Array of module IDs, or regular expressions to match module IDs, that should remain external to the bundle. Can also be just a single ID or regular expression. The matched IDs should be either:

  1. 外部依赖的名称,与 import 语句中的写入方式完全相同。 IE。 要将 import "dependency.js" 标记为外部,请使用 "dependency.js";要将 import "dependency" 标记为外部,请使用 "dependency"
  2. 已解析的 ID(如文件的绝对路径)。
js
// 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/
	]
};
// 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/
	]
};

请注意,如果你想过滤掉包导入,例如 import {rollup} from 'rollup',通过 /node_modules/ 正则表达式,你需要像 @rollup/plugin-node-resolve 这样的东西来首先解析到 node_modules 的导入。

Note that if you want to filter out package imports, e.g. import {rollup} from 'rollup', via a /node_modules/ regular expression, you need something like @rollup/plugin-node-resolve to resolve the imports to node_modules first.

当作为命令行参数给出时,它应该是逗号分隔的 ID 列表:

When given as a command line argument, it should be a comma-separated list of IDs:

bash
rollup -i src/main.js ... -e foo,bar,baz
rollup -i src/main.js ... -e foo,bar,baz

提供函数时,使用三个参数 (id, parent, isResolved) 调用它,可以为你提供更细粒度的控制:

When providing a function, it is called with three parameters (id, parent, isResolved) that can give you more fine-grained control:

  • id 是相关模块的 id
  • parent 是执行导入的模块的 id
  • isResolved 表示 id 是否已通过例如以下方法解决: 插件

创建 iifeumd 包时,你需要提供全局变量名称以通过 output.globals 选项替换外部导入。

When creating an iife or umd bundle, you will need to provide global variable names to replace your external imports via the output.globals option.

如果相对导入(即从 ./../ 开始)被标记为 "external",则 rollup 将在内部将 id 解析为绝对文件系统位置,以便可以合并外部模块的不同导入。 当生成的包被写入时,导入将再次转换为相对导入。 例子:

If a relative import, i.e. starting with ./ or ../, is marked as "external", rollup will internally resolve the id to an absolute file system location so that different imports of the external module can be merged. When the resulting bundle is written, the import will again be converted to a relative import. Example:

js
// 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);
// 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.fileoutput.dir 与入口点或所有入口点的公共基目录(如果有多个入口点)位于同一位置一样。

The conversion back to a relative import is done as if output.file or output.dir were in the same location as the entry point or the common base directory of all entry points if there is more than one.

input

类型:string | string []| { [entryName: string]: string }
命令行接口:-i/--input <filename>

打包包的入口点(例如你的 main.jsapp.jsindex.js)。 如果你提供入口点数组或将名称映射到入口点的对象,它们将被打包到单独的输出块中。 除非使用 output.file 选项,否则生成的块名称将遵循 output.entryFileNames 选项。 当使用对象形式时,文件名的 [name] 部分将是对象属性的名称,而对于数组形式,它将是入口点的文件名。

The bundle's entry point(s) (e.g. your main.js or app.js or index.js). If you provide an array of entry points or an object mapping names to entry points, they will be bundled to separate output chunks. Unless the output.file option is used, generated chunk names will follow the output.entryFileNames option. When using the object form, the [name] portion of the file name will be the name of the object property while for the array form, it will be the file name of the entry point.

请注意,使用对象形式时可以通过在名称中添加 / 将入口点放入不同的子文件夹中。 下面将生成至少两个名为 entry-a.jsentry-b/index.js 的条目块,即文件 index.js 放置在文件夹 entry-b 中:

Note that it is possible when using the object form to put entry points into different sub-folders by adding a / to the name. The following will generate at least two entry chunks with the names entry-a.js and entry-b/index.js, i.e. the file index.js is placed in the folder entry-b:

js
// rollup.config.js
export default {
  ...,
  input: {
    a: 'src/main-a.js',
    'b/index': 'src/main-b.js'
  },
  output: {
    ...,
    entryFileNames: 'entry-[name].js'
  }
};
// rollup.config.js
export default {
  ...,
  input: {
    a: 'src/main-a.js',
    'b/index': 'src/main-b.js'
  },
  output: {
    ...,
    entryFileNames: 'entry-[name].js'
  }
};

如果你想将一组文件转换为另一种格式,同时保持文件结构和导出签名,推荐的方法—而不是使用 output.preserveModules ,它可能会摇动导出并触发由插件创建的虚拟文件—就是把每个文件变成一个入口点。 你可以动态地执行此操作,例如 通过 glob 包:

If you want to convert a set of files to another format while maintaining the file structure and export signatures, the recommended way—instead of using output.preserveModules that may tree-shake exports as well as emit virtual files created by plugins—is to turn every file into an entry point. You can do so dynamically e.g. via the glob package:

js
import glob from 'glob';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

export default {
	input: Object.fromEntries(
		glob.sync('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'
	}
};
import glob from 'glob';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

export default {
	input: Object.fromEntries(
		glob.sync('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),则可以省略该选项。

The option can be omitted if some plugin emits at least one chunk (using this.emitFile) by the end of the buildStart hook.

使用命令行接口时,可以通过多次使用该选项来提供多个输入。 当作为第一个选项提供时,相当于不使用 --input 前缀:

When using the command line interface, multiple inputs can be provided by using the option multiple times. When provided as the first options, it is equivalent to not prefix them with --input:

shell
rollup --format es --input src/entry1.js --input src/entry2.js
# is equivalent to
rollup src/entry1.js src/entry2.js --format es
rollup --format es --input src/entry1.js --input src/entry2.js
# is equivalent to
rollup src/entry1.js src/entry2.js --format es

可以通过将 = 添加到提供的值来命名块:

Chunks can be named by adding an = to the provided value:

shell
rollup main=src/entry1.js other=src/entry2.js --format es
rollup main=src/entry1.js other=src/entry2.js --format es

可以使用引号指定包含空格的文件名:

File names containing spaces can be specified by using quotes:

shell
rollup "main entry"="src/entry 1.js" "src/other entry.js" --format es
rollup "main entry"="src/entry 1.js" "src/other entry.js" --format es

output.dir

类型:string
命令行接口:-d/--dir <dirname>

放置所有生成块的目录。 如果生成多个块,则需要此选项。 否则,可以使用 file 选项来代替。

The directory in which all generated chunks are placed. This option is required if more than one chunk is generated. Otherwise, the file option can be used instead.

output.file

类型:string
命令行接口:-o/--file <filename>

要写入的文件。 如果适用的话,还将用于生成源映射。 仅当生成的块不超过 1 个时才可使用。

The file to write to. Will also be used to generate sourcemaps, if applicable. Can only be used if not more than one chunk is generated.

output.format

类型:string
命令行接口:-f/--format <formatspecifier>
默认:"es"

指定生成的包的格式。 以下之一:

Specifies the format of the generated bundle. One of the following:

  • amd – 异步模块定义,与 RequireJS 等模块加载器一起使用
  • cjs – CommonJS,适用于 Node 和其他打包器(别名:commonjs
  • es – 将打包包保留为 ES 模块文件,适合其他打包程序并作为 <script type=module> 标签包含在现代浏览器中(别名:esmmodule
  • iife – 自执行函数,适合作为 <script> 标签包含在内。 (如果你想为你的应用创建打包包,你可能需要使用它。)。 "生活" 代表 "立即调用 函数表达式"
  • umd – 通用模块定义,可作为 amdcjsiife 合一使用
  • system – SystemJS 加载器的原生格式(别名:systemjs

output.globals

类型:{ [id: string]: string }| ((id: string) => string)
命令行接口:-g/--globals <external-id:variableName,another-external-id:anotherVariableName,...>

指定 umd/iife 打包包中外部导入所需的 id: variableName 对。 例如,在这样的情况下......

Specifies id: variableName pairs necessary for external imports in umd/iife bundles. For example, in a case like this…

js
import $ from 'jquery';
import $ from 'jquery';

…我们想告诉 Rollup jquery 是外部的,jquery 模块 ID 等于全局 $ 变量:

…we want to tell Rollup that jquery is external and the jquery module ID equates to the global $ variable:

js
// rollup.config.js
export default {
  ...,
  external: ['jquery'],
  output: {
    format: 'iife',
    name: 'MyBundle',
    globals: {
      jquery: '$'
    }
  }
};

/*
var MyBundle = (function ($) {
  // code goes here
}($));
*/
// rollup.config.js
export default {
  ...,
  external: ['jquery'],
  output: {
    format: 'iife',
    name: 'MyBundle',
    globals: {
      jquery: '$'
    }
  }
};

/*
var MyBundle = (function ($) {
  // code goes here
}($));
*/

或者,提供一个函数将外部模块 ID 转换为全局变量名称。

Alternatively, supply a function that will turn an external module ID into a global variable name.

当作为命令行参数给出时,它应该是逗号分隔的 id:variableName 对列表:

When given as a command line argument, it should be a comma-separated list of id:variableName pairs:

shell
rollup -i src/main.js ... -g jquery:$,underscore:_
rollup -i src/main.js ... -g jquery:$,underscore:_

要告诉 Rollup 本地文件应该替换为全局变量,请使用绝对 id:

To tell Rollup that a local file should be replaced by a global variable, use an absolute id:

js
// 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'
		}
	}
};
// 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
命令行接口:-n/--name <variableName>

对于导出值的 iife/umd 包是必需的,在这种情况下,它是代表你的包的全局变量名称。 同一页面上的其他脚本可以使用此变量名称来访问打包包的导出。

Necessary for iife/umd bundles that exports values in which case it is the global variable name representing your bundle. Other scripts on the same page can use this variable name to access the exports of your bundle.

js
// rollup.config.js
export default {
  ...,
  output: {
    file: 'bundle.js',
    format: 'iife',
    name: 'MyBundle'
  }
};

// var MyBundle = (function () {...
// rollup.config.js
export default {
  ...,
  output: {
    file: 'bundle.js',
    format: 'iife',
    name: 'MyBundle'
  }
};

// var MyBundle = (function () {...

支持命名空间,即你的名称可以包含点。 生成的包将包含命名空间所需的设置。

Namespaces are supported i.e. your name can contain dots. The resulting bundle will contain the setup necessary for the namespacing.

shell
rollup -n "a.b.c"

/* ->
this.a = this.a || {};
this.a.b = this.a.b || {};
this.a.b.c = ...
*/
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)。 Falsy 插件将被忽略,可用于轻松激活或停用插件。 嵌套插件将被展平。 异步插件将等待并解决。

Adds a plugin just to this output. See Using output plugins for more information on how to use output-specific plugins and Plugins on how to write your own. For plugins imported from packages, remember to call the imported plugin function (i.e. commonjs(), not just commonjs). Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins. Nested plugins will be flattened. Async plugin will be awaited and resolved.

并非所有插件都可以在这里使用。 output.plugins 仅限于仅使用在 bundle.generate()bundle.write() 期间(即 Rollup 的主要分析完成后)运行的钩子的插件。 如果你是插件作者,请参阅 输出生成钩子 以了解可以使用哪些钩子。

Not every plugin can be used here. output.plugins is limited to plugins that only use hooks that run during bundle.generate() or bundle.write(), i.e. after Rollup's main analysis is complete. If you are a plugin author, see output generation hooks to find out which hooks can be used.

以下内容将为输出之一添加缩小功能:

The following will add minification to one of the outputs:

js
// 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()]
		}
	]
};
// 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)。 Falsy 插件将被忽略,可用于轻松激活或停用插件。 嵌套插件将被展平。 异步插件将等待并解决。

See Using plugins for more information on how to use plugins and Plugins on how to write your own (try it out, it's not as difficult as it may sound and very much extends what you can do with Rollup). For plugins imported from packages, remember to call the imported plugin function (i.e. commonjs(), not just commonjs). Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins. Nested plugins will be flatten. Async plugins will be awaited and resolved.

js
// 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'
	}
}))();
// 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 和动态导入来避免不必要的模块加载,这可能会非常慢。)

(This example also demonstrates how to use an async IIFE and dynamic imports to avoid unnecessary module loading, which can be surprisingly slow.)

高级功能

cache

类型:RollupCache | boolean
默认:true

先前打包包的 cache 属性。 用它来加速监视模式下的后续构建 — Rollup 只会重新分析已更改的模块。 将此选项显式设置为 false 将阻止在打包包上生成 cache 属性,并停用插件的缓存。

The cache property of a previous bundle. Use it to speed up subsequent builds in watch mode — Rollup will only reanalyse the modules that have changed. Setting this option explicitly to false will prevent generating the cache property on the bundle and also deactivate caching for plugins.

js
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
	});
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"
命令行接口:--logLevel <level>
默认:"info"

确定要处理哪些日志。 请参阅 onLog 了解可用的日志级别。 "info" 的默认 logLevel 意味着信息和警告日志将被处理,而调试日志将被吞掉,这意味着它们既不会传递给插件 onLog 钩子,也不会传递给 onLog 选项或打印到控制台。

Determine which logs to process. See onLog for the available log levels. The default logLevel of "info" means that info and warnings logs will be processed while debug logs will be swallowed, which means that they are neither passed to plugin onLog hooks nor the onLog option or printed to the console.

使用 CLI 时,错误仍会打印到控制台,因为它们不通过日志记录系统进行处理。 有关如何抑制错误日志的信息,请参阅 --silent 标志。

When using the CLI, errors will still be printed to the console as they are not processed via the logging system. See the --silent flag for how to suppress error logs.

makeAbsoluteExternalsRelative

类型:boolean| "ifRelativeSource"
命令行接口:--makeAbsoluteExternalsRelative/--no-makeAbsoluteExternalsRelative
默认:"ifRelativeSource"

确定是否应将绝对外部路径转换为输出中的相对路径。 这不仅适用于源中的绝对路径,还适用于由插件或 Rollup 核心解析为绝对路径的路径。

Determines if absolute external paths should be converted to relative paths in the output. This does not only apply to paths that are absolute in the source but also to paths that are resolved to an absolute path by either a plugin or Rollup core.

对于 true,像 import "/Users/Rollup/project/relative.js" 这样的外部导入将被转换为相对路径。 将绝对路径转换为相对路径时,Rollup 不会考虑 filedir 选项,因为这些选项可能不存在,例如 用于使用 JavaScript API 进行构建。 相反,它假设生成的包的根位于该包中包含的所有模块的公共共享父目录。 假设所有模块的公共父目录是 "/Users/Rollup/project",则上面的导入可能会在输出中转换为 import "./relative.js"。 如果输出块本身通过选择例如嵌套在子目录中 chunkFileNames: "chunks/[name].js",导入将为 "../relative.js"

For true, an external import like import "/Users/Rollup/project/relative.js" would be converted to a relative path. When converting an absolute path to a relative path, Rollup does not take the file or dir options into account, because those may not be present e.g. for builds using the JavaScript API. Instead, it assumes that the root of the generated bundle is located at the common shared parent directory of all modules that were included in the bundle. Assuming that the common parent directory of all modules is "/Users/Rollup/project", the import from above would likely be converted to import "./relative.js" in the output. If the output chunk is itself nested in a subdirectory by choosing e.g. chunkFileNames: "chunks/[name].js", the import would be "../relative.js".

如前所述,这也适用于像 import "./relative.js" 这样的原始相对导入,这些导入在被 external 选项标记为外部之前解析为绝对路径。

As stated before, this would also apply to originally relative imports like import "./relative.js" that are resolved to an absolute path before they are marked as external by the external option.

一个常见的问题是,这种机制也适用于像 import "/absolute.js'" 这样的导入,导致输出中出现意外的相对路径。

One common problem is that this mechanism will also apply to imports like import "/absolute.js'", resulting in unexpected relative paths in the output.

对于这种情况,"ifRelativeSource" 检查原始导入是否是相对导入,然后才将其转换为输出中的相对导入。 选择 false 会将所有路径保留为输出中的绝对路径。

For this case, "ifRelativeSource" checks if the original import was a relative import and only then convert it to a relative import in the output. Choosing false will keep all paths as absolute paths in the output.

请注意,当使用 external 选项将相对路径直接标记为 "external" 时,输出中将是相同的相对路径。 当它首先通过插件或 Rollup 核心解决,然后标记为外部时,将应用上述逻辑。

Note that when a relative path is directly marked as "external" using the external option, then it will be the same relative path in the output. When it is resolved first via a plugin or Rollup core and then marked as external, the above logic will apply.

maxParallelFileOps

类型:number
命令行接口:--maxParallelFileOps <number>
默认:20

限制读取模块或写入块时并行打开的文件数量。 如果没有限制或值足够高,构建可能会失败并显示 "EMFILE:打开的文件太多"。 这取决于操作系统允许的打开文件句柄数。

Limits the number of files rollup will open in parallel when reading modules or writing chunks. Without a limit or with a high enough value, builds can fail with an "EMFILE: too many open files". This depends on how many open file handles the operating system allows.

onLog

类型:(level: LogLevel, log: RollupLog, defaultHandler: LogOrStringHandler) => void;
typescript
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;
}
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 选项时也会触发此处理程序。

A function that intercepts log messages. If not supplied, logs are printed to the console, whereby Rollup CLI aggregates certain "warn" logs and prints consolidated warnings after the build to reduce noise. This handler is also triggered when using the --silent CLI option.

该函数接收三个参数: 日志级别、日志对象和默认处理程序。 日志对象至少具有 codemessage 属性,允许你控制如何处理不同类型的日志。 根据日志类型添加其他属性。 有关内置错误和日志及其代码和属性的完整列表,请参阅 utils/logs.ts

The function receives three arguments: the log level, the log object and the default handler. Log objects have, at a minimum, a code and a message property, allowing you to control how different kinds of logs are handled. Other properties are added depending on the type of log. See utils/logs.ts for a complete list of built-in errors and logs together with their codes and properties.

如果不调用默认处理程序,日志将不会打印到控制台。 此外,你可以通过调用不同级别的默认处理程序来更改日志级别。 使用附加级别 "error" 会将日志转换为抛出的错误,其中附加了日志的所有属性。

If the default handler is not invoked, the log will not be printed to the console. Moreover, you can change the log level by invoking the default handler with a different level. Using the additional level "error" will turn the log into a thrown error that has all properties of the log attached.

js
// 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
		}
	}
};
// 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 选项过滤掉,则不会调用此处理程序。 IE。 默认情况下,"debug" 条日志将被吞掉。

This handler will not be invoked if logs are filtered out by the logLevel option. I.e. by default, "debug" logs will be swallowed.

有些日志还具有 loc 属性和 frame,允许你找到日志的来源:

Some logs also have a loc property and a frame allowing you to locate the source of the log:

js
// 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);
		}
	}
};
// 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 非常相似,但仅收到警告。 如果调用默认处理程序,日志将作为警告处理。 如果同时提供了 onLogonwarn 处理程序,则仅当 onLog 使用 levelwarn 调用其默认处理程序时,才会调用 onwarn 处理程序。

A function that will intercept warning messages. It is very similar to onLog but only receives warnings. If the default handler is invoked, the log will be handled as a warning. If both an onLog and onwarn handler are provided, the onwarn handler will only be invoked if onLog calls its default handler with a level of warn.

请参阅 onLog 了解更多信息。

See onLog for more information.

output.assetFileNames

类型:string| ((assetInfo: AssetInfo) => string)
命令行接口:--assetFileNames <pattern>
默认:"assets/[name]-[hash][extname]"

用于命名要包含在构建输出中的自定义触发资源的模式,或每个资源调用的函数以返回此类模式。 模式支持以下占位符:

The pattern to use for naming custom emitted assets to include in the build output, or a function that is called per asset to return such a pattern. Patterns support the following placeholders:

  • [extname]: 资源的文件扩展名,包括前导点,例如 .css
  • [ext]: 没有前导点的文件扩展名,例如 css
  • [hash]: 基于资源内容的哈希值。 你还可以通过例如设置特定的哈希长度 [hash:10]
  • [name]: 资源的文件名,不包括任何扩展名。

正斜杠 / 可用于将文件放置在子目录中。 使用函数时,assetInfogenerateBundle 中的函数的简化版本,不含 fileName。 另见 output.chunkFileNamesoutput.entryFileNames

Forward slashes / can be used to place files in sub-directories. When using a function, assetInfo is a reduced version of the one in generateBundle without the fileName. See also output.chunkFileNames, output.entryFileNames.

类型:string | ((chunk: ChunkInfo) => string| Promise<string>)
命令行接口:--banner/--footer <text>

要添加到打包包之前/附加到打包包的字符串。 你还可以提供一个返回 Promise 的函数,该 Promise 解析为 string 以异步生成它(注意:bannerfooter 选项不会破坏源映射)。

A string to prepend/append to the bundle. You can also supply a function that returns a Promise that resolves to a string to generate it asynchronously (Note: banner and footer options will not break sourcemaps).

如果你提供一个函数,chunk 包含有关使用与 generateBundle 钩子相同的 ChunkInfo 类型的块的附加信息,但存在以下差异:

If you supply a function, chunk contains additional information about the chunk using the same ChunkInfo type as the generateBundle hook with the following differences:

  • codemap 未设置,因为块尚未渲染。
  • 所有包含哈希值的引用块文件名将包含哈希占位符。 这包括 fileNameimportsimportedBindingsdynamicImportsimplicitlyLoadedBefore。 当你在此选项返回的代码中使用此类占位符文件名或其中的一部分时,Rollup 会将占位符替换为 generateBundle 之前的实际哈希值,确保哈希值反映最终生成的块的实际内容,包括所有引用的文件哈希值 。

chunk 是可变的,在此钩子中应用的更改将传播到其他插件和生成的包。 这意味着如果你在此钩子中添加或删除导入或导出,则应该更新 importsimportedBindings 和/或 exports

chunk is mutable and changes applied in this hook will propagate to other plugins and to the generated bundle. That means if you add or remove imports or exports in this hook, you should update imports, importedBindings and/or exports.

js
// rollup.config.js
export default {
  ...,
  output: {
    ...,
    banner: '/* my-library version ' + version + ' */',
    footer: '/* follow me on Twitter! @rich_harris */'
  }
};
// rollup.config.js
export default {
  ...,
  output: {
    ...,
    banner: '/* my-library version ' + version + ' */',
    footer: '/* follow me on Twitter! @rich_harris */'
  }
};

另见 output.intro/output.outro

See also output.intro/output.outro.

output.chunkFileNames

类型:string | ((chunkInfo: ChunkInfo) => string)
命令行接口:--chunkFileNames <pattern>
默认:"[name]-[hash].js"

用于命名代码分割时创建的共享块的模式,或每个块调用以返回此类模式的函数。 模式支持以下占位符:

The pattern to use for naming shared chunks created when code-splitting, or a function that is called per chunk to return such a pattern. Patterns support the following placeholders:

  • [format]: 输出选项中定义的渲染格式,例如 escjs
  • [hash]: 仅基于最终生成的块的内容的哈希,包括 renderChunk 中的转换和任何引用的文件哈希。 你还可以通过例如设置特定的哈希长度 [hash:10]
  • [name]: 块的名称。 这可以通过 output.manualChunks 选项显式设置,或者当块是由插件通过 this.emitFile 创建时显式设置。 否则,它将从块内容中导出。

正斜杠 / 可用于将文件放置在子目录中。 使用函数时,chunkInfogenerateBundle 中函数的简化版本,没有依赖于文件名的属性,也没有有关渲染模块的信息,因为渲染仅在生成文件名后发生。 不过,你可以访问包含的 moduleIds 列表。 另见 output.assetFileNamesoutput.entryFileNames

Forward slashes / can be used to place files in sub-directories. When using a function, chunkInfo is a reduced version of the one in generateBundle without properties that depend on file names and no information about the rendered modules as rendering only happens after file names have been generated. You can however access a list of included moduleIds. See also output.assetFileNames, output.entryFileNames.

output.compact

类型:boolean
命令行接口:--compact/--no-compact
默认:false

这将缩小由 Rollup 生成的封装器代码。 请注意,这不会影响用户编写的代码。 当打包预先缩小的代码时,此选项非常有用。

This will minify the wrapper code generated by rollup. Note that this does not affect code written by the user. This option is useful when bundling pre-minified code.

output.dynamicImportInCjs

类型:boolean
命令行接口:--dynamicImportInCjs/--no-dynamicImportInCjs
默认:true

虽然 CommonJS 输出最初仅支持 require(…) 导入依赖,但最近的 Node 版本也开始支持 import(…),这是从 CommonJS 文件导入 ES 模块的唯一方法。 如果此选项为 true(默认值),Rollup 将在 CommonJS 输出中将外部动态导入保留为 import(…) 表达式。 将其设置为 false 以使用 require(…) 语法重写动态导入。

While CommonJS output originally supported only require(…) to import dependencies, recent Node versions also started to support import(…), which is the only way to import ES modules from CommonJS files. If this option is true, which is the default, Rollup will keep external dynamic imports as import(…) expressions in CommonJS output. Set this to false to rewrite dynamic imports using require(…) syntax.

js
// 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);
// 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)
命令行接口:--entryFileNames <pattern>
默认:"[name].js"

用于从入口点创建的块的模式,或每个入口块调用以返回此类模式的函数。 模式支持以下占位符:

The pattern to use for chunks created from entry points, or a function that is called per entry chunk to return such a pattern. Patterns support the following placeholders:

  • [format]: 输出选项中定义的渲染格式,例如 escjs
  • [hash]: 仅基于最终生成的条目块的内容的哈希,包括 renderChunk 中的转换和任何引用的文件哈希。 你还可以通过例如设置特定的哈希长度 [hash:10]
  • [name]: 入口点的文件名(不带扩展名),除非使用输入的对象形式定义不同的名称。

正斜杠 / 可用于将文件放置在子目录中。 使用函数时,chunkInfogenerateBundle 中函数的简化版本,没有依赖于文件名的属性,也没有有关渲染模块的信息,因为渲染仅在生成文件名后发生。 不过,你可以访问包含的 moduleIds 列表。 另见 output.assetFileNamesoutput.chunkFileNames

Forward slashes / can be used to place files in sub-directories. When using a function, chunkInfo is a reduced version of the one in generateBundle without properties that depend on file names and no information about the rendered modules as rendering only happens after file names have been generated. You can however access a list of included moduleIds. See also output.assetFileNames, output.chunkFileNames.

设置 output.preserveModules 选项时,此模式也将用于每个文件。 请注意,在这种情况下,[name] 将包括来自输出根目录的相对路径,如果它不是 .js.jsx.mjs.cjs.ts.tsx.mts.cts 之一,则可能还包括原始文件扩展名。

This pattern will also be used for every file when setting the output.preserveModules option. Note that in this case, [name] will include the relative path from the output root and possibly the original file extension if it was not one of .js, .jsx, .mjs, .cjs, .ts, .tsx, .mts, or .cts.

output.extend

类型:boolean
命令行接口:--extend/--no-extend
默认:false

是否以 umdiife 格式扩展 name 选项定义的全局变量。 当 true 时,全局变量将被定义为 (global.name = global.name || {})。 当为 false 时,name 定义的全局将像 (global.name = {}) 一样被覆盖。

Whether to extend the global variable defined by the name option in umd or iife formats. When true, the global variable will be defined as (global.name = global.name || {}). When false, the global defined by name will be overwritten like (global.name = {}).

output.externalImportAttributes

类型:boolean
命令行接口:--externalImportAttributes/--no-externalImportAttributes
默认:true

如果输出格式为 es,是否在输出中为外部导入添加导入属性。 默认情况下,属性是从输入文件中获取的,但插件可以稍后添加或删除属性。 例如。 除非该选项设置为 false,否则 import "foo" assert {type: "json"} 将导致相同的导入出现在输出中。 请注意,模块的所有导入都需要具有一致的属性,否则会触发警告。

Whether to add import attributes to external imports in the output if the output format is es. By default, attributes are taken from the input files, but plugins can add or remove attributes later. E.g. import "foo" assert {type: "json"} will cause the same import to appear in the output unless the option is set to false. Note that all imports of a module need to have consistent attributes, otherwise a warning is emitted.

output.generatedCode

类型:"es5" | "es2015"| { arrowFunctions?: boolean, constBindings?: boolean, objectShorthand?: boolean, preset?: "es5"| "es2015", reservedNamesAsProps?: boolean, symbols?: boolean }
命令行接口:--generatedCode <preset>
默认:"es5"

Rollup 可以在生成的代码中安全地使用哪些语言功能。 这不会转译任何用户代码,而只会更改 Rollup 在封装器和辅助程序中使用的代码。 你可以选择以下几个预设之一:

Which language features Rollup can safely use in generated code. This will not transpile any user code but only change the code Rollup uses in wrappers and helpers. You may choose one of several presets:

  • "es5": 不要使用 ES2015+ 功能(例如箭头函数),但不要引用用作 props 的保留名称。
  • "es2015": 使用 ES2015 之前的任何 JavaScript 功能。

output.generatedCode.arrowFunctions

类型:boolean
命令行接口:--generatedCode.arrowFunctions/--no-generatedCode.arrowFunctions
默认:false

是否对自动生成的代码片段使用箭头函数。 请注意,在某些地方(例如模块封装器),Rollup 将继续使用括在括号中的常规函数,就像在某些 JavaScript 引擎中一样,这些将提供 性能明显更好

Whether to use arrow functions for auto-generated code snippets. Note that in certain places like module wrappers, Rollup will keep using regular functions wrapped in parentheses as in some JavaScript engines, these will provide noticeably better performance.

output.generatedCode.constBindings

类型:boolean
命令行接口:--generatedCode.constBindings/--no-generatedCode.constBindings
默认:false

这将在某些地方和辅助函数中使用 const 而不是 var。 由于块作用域,这将允许 Rollup 生成更高效的助手。

This will use const instead of var in certain places and helper functions. This will allow Rollup to generate more efficient helpers due to block scoping.

js
// 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]
		});
}
// 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

类型:boolean
命令行接口:--generatedCode.objectShorthand/--no-generatedCode.objectShorthand
默认:false

当属性名称与值匹配时,允许在对象中使用简写符号。

Allows the use of shorthand notation in objects when the property name matches the value.

javascript
// 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 });
		}
	};
});
// 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"
命令行接口:--generatedCode <value>

允许选择上面列出的预设之一,同时覆盖某些选项。

Allows choosing one of the presets listed above while overriding some options.

js
export default {
	// ...
	output: {
		generatedCode: {
			preset: 'es2015',
			arrowFunctions: false
		}
		// ...
	}
};
export default {
	// ...
	output: {
		generatedCode: {
			preset: 'es2015',
			arrowFunctions: false
		}
		// ...
	}
};

output.generatedCode.reservedNamesAsProps

类型:boolean
命令行接口:--generatedCode.reservedNamesAsProps/--no-generatedCode.reservedNamesAsProps
默认:true

确定保留字(如 "默认")是否可以用作属性名称而不使用引号。 这将使生成的代码的语法符合 ES3。 但请注意,为了完全符合 ES3,你可能还需要填充一些内置函数,例如 Object.keysArray.prototype.forEach

Determine whether reserved words like "default" can be used as prop names without using quotes. This will make the syntax of the generated code ES3 compliant. Note however that for full ES3 compliance, you may also need to polyfill some builtin functions like Object.keys or Array.prototype.forEach.

javascript
// 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;
// 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

类型:boolean
命令行接口:--generatedCode.symbols/--no-generatedCode.symbols
默认:false

是否允许在自动生成的代码片段中使用 Symbol。 目前,这仅控制命名空间是否将 Symbol.toStringTag 属性设置为 Module 的正确值,这意味着对于命名空间,String(namespace) 记录 [object Module]。 这再次用于某些库和框架中的特性检测。

Whether to allow the use of Symbol in auto-generated code snippets. Currently, this only controls if namespaces will have the Symbol.toStringTag property set to the correct value of Module, which means that for a namespace, String(namespace) logs [object Module]. This again is used for feature detection in certain libraries and frameworks.

javascript
// 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;
// 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.hoistTransitiveImports

类型:boolean
命令行接口:--hoistTransitiveImports/--no-hoistTransitiveImports
默认:true

默认情况下,创建多个块时,条目块的传递导入将作为空导入添加到条目块中。 有关详细信息和背景,请参阅 "为什么在代码分割时我的条目块中会出现额外的导入?"。 将此选项设置为 false 将禁用此行为。 使用 output.preserveModules 选项时会忽略此选项,因为这里永远不会提升导入。

By default, when creating multiple chunks, transitive imports of entry chunks will be added as empty imports to the entry chunks. See "Why do additional imports turn up in my entry chunks when code-splitting?" for details and background. Setting this option to false will disable this behaviour. This option is ignored when using the output.preserveModules option as here, imports will never be hoisted.

output.inlineDynamicImports

类型:boolean
命令行接口:--inlineDynamicImports/--no-inlineDynamicImports
默认:false

这将内联动态导入,而不是创建新的块来创建单个包。 仅当提供单个输入时才可能。 请注意,这将更改执行顺序: 如果动态导入是内联的,则仅动态导入的模块将立即执行。

This will inline dynamic imports instead of creating new chunks to create a single bundle. Only possible if a single input is provided. Note that this will change the execution order: A module that is only imported dynamically will be executed immediately if the dynamic import is inlined.

output.interop

类型:"compat" | "auto"| "esModule"| "default"| "defaultOnly"| ((id: string) => "compat"| "auto"| "esModule"| "default"| "defaultOnly")
命令行接口:--interop <value>
默认:"default"

控制 Rollup 如何处理来自外部依赖的默认、命名空间和动态导入(采用 CommonJS 等格式,而这些格式本身并不支持这些概念)。 请注意,"默认" 的默认模式模仿 NodeJS 行为,与 TypeScript esModuleInterop 不同。 要获取 TypeScript 的行为,请显式将该值设置为 "auto"。 在示例中,我们将使用 CommonJS 格式,但互操作性的选择也同样适用于 AMD、IIFE 和 UMD 目标。

Controls how Rollup handles default, namespace and dynamic imports from external dependencies in formats like CommonJS that do not natively support these concepts. Note that the default mode of "default" mimics NodeJS behavior and is different from TypeScript esModuleInterop. To get TypeScript's behavior, explicitly set the value to "auto". In the examples, we will be using the CommonJS format, but the choice of interop similarly applies to AMD, IIFE and UMD targets as well.

为了理解不同的值,假设我们为 cjs 目标打包以下代码:

To understand the different values, assume we are bundling the following code for a cjs target:

js
import ext_default, * as external from 'external1';
console.log(ext_default, external.bar, external);
import('external2').then(console.log);
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); 完全等效,并且将生成相同的代码。 然而,在上面的示例中,命名空间对象本身也被传递给全局函数,这意味着我们需要它作为正确形成的对象。

Keep in mind that for Rollup, import * as ext_namespace from 'external'; console.log(ext_namespace.bar); is completely equivalent to import {bar} from 'external'; console.log(bar); and will produce the same code. In the example above however, the namespace object itself is passed to a global function as well, which means we need it as a properly formed object.

  • "default" 假设所需的值应被视为导入模块的默认导出,就像从 NodeJS 中的 ES 模块上下文导入 CommonJS 一样。 还支持命名导入,这些导入被视为默认导入的属性。 为了创建命名空间对象,Rollup 注入了这些助手:

    js
    var 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);
    var 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 属性。 这是唯一不会注入任何辅助函数的互操作类型:

    js
    var external = require('external1');
    console.log(external.default, external.bar, external);
    Promise.resolve()
    	.then(function () {
    		return require('external2');
    	})
    	.then(console.log);
    var 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 属性 的代码。 添加此属性是由 TypeScript esModuleInterop、Babel 和其他工具实现的 hack,用于表示所需的值是转译的 ES 模块的名称空间:

    js
    var 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);
    var 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);
    // 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" 的罕见情况外,这通常有助于实现互操作 "只是工作",因为它不依赖于特殊的 hack,而是使用动态类型:

    js
    var 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);
    var 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);
    // 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" 类似,但以下内容除外:

    • 禁止命名导入。 如果遇到这样的导入,即使是 essystem 格式,Rollup 也会抛出错误。 这样就可以确保 es 版本的代码能够正确导入 Node 中的非内置 CommonJS 模块。
    • 虽然名称空间重新导出 export * from 'external'; 未被禁止,但它们会被忽略,并会导致 Rollup 显示警告,因为如果没有命名导出,它们不会产生任何影响。
    • 当生成命名空间对象时,Rollup 使用一个更简单的辅助程序。

    以下是 Rollup 将从示例代码创建的内容。 请注意,我们从代码中删除了 external.bar,否则 Rollup 会抛出错误,因为如前所述,这相当于命名导入。

    js
    var 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);
    var 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';
    		}
    	}
    };
    // 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';
    		}
    	}
    };

还有一些附加选项会对生成的互操作代码产生影响:

There are some additional options that have an effect on the generated interop code:

  • output.externalLiveBindings 设置为 false 将生成简化的命名空间辅助程序以及提取的默认导入的简化代码。
  • output.freeze 设置为 false 将防止生成的互操作命名空间对象被冻结。

output.intro/output.outro

类型:string | ((chunk: ChunkInfo) => string| Promise<string>)
命令行接口:--intro/--outro <text>

output.banner/output.footer 类似,不同之处在于代码位于任何特定于格式的封装器内。

Similar to output.banner/output.footer, except that the code goes inside any format-specific wrapper.

js
export default {
	//...,
	output: {
		//...,
		intro: 'const ENVIRONMENT = "production";'
	}
};
export default {
	//...,
	output: {
		//...,
		intro: 'const ENVIRONMENT = "production";'
	}
};

output.manualChunks

类型:{ [chunkAlias: string]: string[] } | ((id: string, {getModuleInfo, getModuleIds}) => string | void)

允许创建自定义共享公共块。 使用对象形式时,每个属性代表一个块,其中包含列出的模块及其所有依赖(如果它们是模块图的一部分),除非它们已经位于另一个手动块中。 块的名称将由属性键确定。

Allows the creation of custom shared common chunks. When using the object form, each property represents a chunk that contains the listed modules and all their dependencies if they are part of the module graph unless they are already in another manual chunk. The name of the chunk will be determined by the property key.

请注意,列出的模块本身不必成为模块图的一部分,如果你正在使用 @rollup/plugin-node-resolve 并使用来自包的深度导入,这会很有用。 例如

Note that it is not necessary for the listed modules themselves to be part of the module graph, which is useful if you are working with @rollup/plugin-node-resolve and use deep imports from packages. For instance

javascript
({
	manualChunks: {
		lodash: ['lodash']
	}
});
({
	manualChunks: {
		lodash: ['lodash']
	}
});

即使你只使用 import get from 'lodash/get' 形式的导入,也会将所有 lodash 模块放入手动块中。

will put all lodash modules into a manual chunk even if you are only using imports of the form import get from 'lodash/get'.

当使用函数形式时,每个解析的模块 ID 将被传递给函数。 如果返回一个字符串,则该模块及其所有依赖将被添加到具有给定名称的手动块中。 例如,这将创建一个 vendor 块,其中包含 node_modules 内的所有依赖:

When using the function form, each resolved module id will be passed to the function. If a string is returned, the module and all its dependency will be added to the manual chunk with the given name. For instance this will create a vendor chunk containing all dependencies inside node_modules:

javascript
function manualChunks(id) {
	if (id.includes('node_modules')) {
		return 'vendor';
	}
}
function manualChunks(id) {
	if (id.includes('node_modules')) {
		return 'vendor';
	}
}

请注意,如果在实际使用相应模块之前触发副作用,则手动块可能会更改应用的行为。

Be aware that manual chunks can change the behaviour of the application if side effects are triggered before the corresponding modules are actually used.

使用函数形式时,manualChunks 将传递一个对象作为第二个参数,其中包含函数 getModuleInfogetModuleIds,其工作方式与插件上下文中的 this.getModuleInfothis.getModuleIds 相同。

When using the function form, manualChunks will be passed an object as second parameter containing the functions getModuleInfo and getModuleIds that work the same way as this.getModuleInfo and this.getModuleIds on the plugin context.

这可用于根据模块在模块图中的位置动态确定模块应放置到哪个手动块中。 例如,考虑这样一个场景,你有一组组件,每个组件动态导入一组翻译后的字符串,即

This can be used to dynamically determine into which manual chunk a module should be placed depending on its position in the module graph. For instance consider a scenario where you have a set of components, each of which dynamically imports a set of translated strings, i.e.

js
// 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');
		// ...
	}
}
// 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');
		// ...
	}
}

如果一起使用很多这样的组件,这将导致大量非常小的块的动态导入: 尽管我们知道同一个 chunk 导入的所有相同语言的语言文件总是会一起使用,但 Rollup 没有这个信息。

If a lot of such components are used together, this will result in a lot of dynamic imports of very small chunks: Even though we know that all language files of the same language that are imported by the same chunk will always be used together, Rollup does not have this information.

以下代码将合并仅由单个入口点使用的相同语言的所有文件:

The following code will merge all files of the same language that are only used by a single entry point:

js
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}`;
		}
	}
}
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

类型:boolean
命令行接口:--minifyInternalExports/--no-minifyInternalExports
默认:true 适用于格式 essystem,或者如果 output.compacttrue,则为 false

默认情况下,对于格式 essystem 或者如果 output.compacttrue,Rollup 将尝试将内部变量导出为单字母变量,以实现更好的缩小。

By default, for formats es and system or if output.compact is true, Rollup will try to export internal variables as single letter variables to allow for better minification.

例子
输入:

Example
Input:

js
// main.js
import './lib.js';

// lib.js
import('./dynamic.js');
export const importantValue = 42;

// dynamic.js
import { importantValue } from './lib.js';
console.log(importantValue);
// 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 的输出:

Output with output.minifyInternalExports: true:

js
// 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);
// 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 的输出:

Output with output.minifyInternalExports: false:

js
// 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);
// 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 },因为压缩器通常不会更改导出签名。

Even though it appears that setting this option to true makes the output larger, it actually makes it smaller if a minifier is used. In this case, export { importantValue as i } can become e.g. export{a as i} or even export{i}, while otherwise it would produce export{ a as importantValue } because a minifier usually will not change export signatures.

output.paths

类型:{ [id: string]: string } | ((id: string) => string)

将外部模块 ID 映射到路径。 外部 id 是 无法解决external 选项明确提供的 id。 output.paths 提供的路径将在生成的包中使用,而不是模块 ID,例如,允许你从 CDN 加载依赖:

Maps external module IDs to paths. External ids are ids that cannot be resolved or ids explicitly provided by the external option. Paths supplied by output.paths will be used in the generated bundle instead of the module ID, allowing you to, for example, load dependencies from a CDN:

js
// 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://d3js.org/d3.v4.min'
		}
	}
};

// bundle.js
define(['https://d3js.org/d3.v4.min'], function (d3) {
	d3.selectAll('p').style('color', 'purple');
	// ...
});
// 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://d3js.org/d3.v4.min'
		}
	}
};

// bundle.js
define(['https://d3js.org/d3.v4.min'], function (d3) {
	d3.selectAll('p').style('color', 'purple');
	// ...
});

output.preserveModules

类型:boolean
命令行接口:--preserveModules/--no-preserveModules
默认:false

此模式不会创建尽可能少的块,而是使用原始模块名称作为文件名为所有模块创建单独的块。 需要 output.dir 选项。 仍将应用树摇动,抑制所提供的入口点未使用的文件或执行时不会产生副作用的文件,并删除不是入口点的文件的未使用导出。 另一方面,如果插件(如 @rollup/plugin-commonjs)触发额外的 "虚拟的" 文件来实现某些结果,这些文件将使用模式 _virtual/fileName.js 作为实际文件触发。

Instead of creating as few chunks as possible, this mode will create separate chunks for all modules using the original module names as file names. Requires the output.dir option. Tree-shaking will still be applied, suppressing files that are not used by the provided entry points or do not have side effects when executed and removing unused exports of files that are not entry points. On the other hand, if plugins (like @rollup/plugin-commonjs) emit additional "virtual" files to achieve certain results, those files will be emitted as actual files using a pattern _virtual/fileName.js.

因此,如果你想直接从这些文件导入,则不建议盲目使用此选项将整个文件结构转换为另一种格式,因为预期的导出可能会丢失。 在这种情况下,你应该通过将所有文件添加到 input 选项对象 来明确指定所有文件作为入口点,请参阅那里的示例以了解如何执行此操作。

It is therefore not recommended to blindly use this option to transform an entire file structure to another format if you directly want to import from those files as expected exports may be missing. In that case, you should rather designate all files explicitly as entry points by adding them to the input option object, see the example there for how to do that.

请注意,转换为 cjsamd 格式时,每个文件将默认被视为入口点,其中 output.exports 设置为 auto。 这意味着例如 对于 cjs,仅包含默认导出的文件将渲染为

Note that when transforming to cjs or amd format, each file will by default be treated as an entry point with output.exports set to auto. This means that e.g. for cjs, a file that only contains a default export will be rendered as

js
// input main.js
export default 42;

// output main.js
('use strict');

var main = 42;

module.exports = main;
// input main.js
export default 42;

// output main.js
('use strict');

var main = 42;

module.exports = main;

直接将值赋给 module.exports。 如果有人导入此文件,他们将通过以下方式访问默认导出

assigning the value directly to module.exports. If someone imports this file, they will get access to the default export via

js
const main = require('./main.js');
console.log(main); // 42
const main = require('./main.js');
console.log(main); // 42

与常规入口点一样,混合默认导出和命名导出的文件将产生警告。 你可以通过 output.exports: "named" 强制所有文件使用命名导出模式来避免警告。 在这种情况下,需要通过导出的 .default 属性访问默认导出:

As with regular entry points, files that mix default and named exports will produce warnings. You can avoid the warnings by forcing all files to use named export mode via output.exports: "named". In that case, the default export needs to be accessed via the .default property of the export:

js
// 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
// 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
命令行接口:--preserveModulesRoot <directory-name>

output.preserveModulestrue 时,应从 output.dir 路径中剥离输入模块的目录路径。

A directory path to input modules that should be stripped away from output.dir path while output.preserveModules is true.

例如,给出以下配置:

For example, given the following configuration:

javascript
export default {
	input: ['src/module.js', `src/another/module.js`],
	output: [
		{
			format: 'es',
			dir: 'dist',
			preserveModules: true,
			preserveModulesRoot: 'src'
		}
	]
};
export default {
	input: ['src/module.js', `src/another/module.js`],
	output: [
		{
			format: 'es',
			dir: 'dist',
			preserveModules: true,
			preserveModulesRoot: 'src'
		}
	]
};

preserveModulesRoot 设置确保输入模块将输出到路径 dist/module.jsdist/another/module.js

The preserveModulesRoot setting ensures that the input modules will be output to the paths dist/module.js and dist/another/module.js.

当使用诸如 @rollup/plugin-node-resolve 之类的插件时,此选项特别有用,这可能会导致输出目录结构发生变化。 当第三方模块未标记为 external,或者在多个相互依赖且未标记为 external 的包的单一存储库中进行开发时,可能会发生这种情况。

This option is particularly useful while using plugins such as @rollup/plugin-node-resolve, which may cause changes in the output directory structure. This can happen when third-party modules are not marked external, or while developing in a monorepo of multiple packages that rely on one another and are not marked external.

output.sourcemap

类型:boolean | 'inline'| 'hidden'
命令行接口:-m/--sourcemap/--no-sourcemap
默认:false

如果是 true,将创建一个单独的源映射文件。 如果是 "inline",则源映射将作为数据 URI 附加到生成的 output 文件中。 "hidden" 的工作方式与 true 类似,只是打包文件中相应的源映射注释被抑制。

If true, a separate sourcemap file will be created. If "inline", the sourcemap will be appended to the resulting output file as a data URI. "hidden" works like true except that the corresponding sourcemap comments in the bundled files are suppressed.

output.sourcemapBaseUrl

类型:string
命令行接口:--sourcemapBaseUrl <url>

默认情况下,Rollup 生成的源映射文件使用相对 URL 来引用它们所描述的文件。 通过提供绝对基本 URL,例如 https://example.com,源映射将使用绝对 URL。

By default, sourcemap files generated by Rollup uses relative URLs to reference the files they describe. By providing an absolute base URL, e.g. https://example.com, sourcemaps will use absolute URLs instead.

output.sourcemapExcludeSources

类型:boolean
命令行接口:--sourcemapExcludeSources/--no-sourcemapExcludeSources
默认:false

如果是 true,源的实际代码将不会添加到源映射中,从而使它们变得相当小。

If true, the actual code of the sources will not be added to the sourcemaps, making them considerably smaller.

output.sourcemapFile

类型:string
命令行接口:--sourcemapFile <file-name-with-path>

生成的包的位置。 如果这是绝对路径,则源映射中的所有 sources 路径都将相对于它。 map.file 属性是 sourcemapFile 的基本名称,因为假定源映射的位置与包相邻。

The location of the generated bundle. If this is an absolute path, all the sources paths in the sourcemap will be relative to it. The map.file property is the basename of sourcemapFile, as the location of the sourcemap is assumed to be adjacent to the bundle.

如果指定了 output,则不需要 sourcemapFile,在这种情况下,将通过将 ".map" 添加到打包包的输出文件名来推断输出文件名。

sourcemapFile is not required if output is specified, in which case an output filename will be inferred by adding ".map" to the output filename for the bundle.

output.sourcemapFileNames

类型:string | ((chunkInfo: ChunkInfo) => string)
命令行接口:--sourcemapFileNames <pattern>

用于源映射的模式,或每个源映射调用以返回此类模式的函数。 模式支持以下占位符:

The pattern to use for sourcemaps, or a function that is called per sourcemap to return such a pattern. Patterns support the following placeholders:

  • [format]: 输出选项中定义的渲染格式,例如 escjs
  • [hash]: 仅基于最终生成的源映射的内容的哈希。 你还可以通过例如设置特定的哈希长度 [hash:10]
  • [chunkhash]: 与用于相应生成块(如果有)的散列相同。
  • [name]: 入口点的文件名(不带扩展名),除非使用输入的对象形式定义不同的名称。

正斜杠 / 可用于将文件放置在子目录中。 使用函数时,chunkInfogenerateBundle 中函数的简化版本,没有依赖于文件名的属性,也没有有关渲染模块的信息,因为渲染仅在生成文件名后发生。 不过,你可以访问包含的 moduleIds 列表。 另见 output.assetFileNamesoutput.chunkFileNames

Forward slashes / can be used to place files in sub-directories. When using a function, chunkInfo is a reduced version of the one in generateBundle without properties that depend on file names and no information about the rendered modules as rendering only happens after file names have been generated. You can however access a list of included moduleIds. See also output.assetFileNames, output.chunkFileNames.

output.sourcemapIgnoreList

类型:boolean | (relativeSourcePath: string, sourcemapPath: string) => boolean

用于决定是否忽略列出源映射中的源文件的谓词,用于填充 x_google_ignoreList 源映射扩展relativeSourcePath 是从生成的 .map 文件到相应源文件的相对路径,而 sourcemapPath 是生成的源映射文件的完全解析路径。

A predicate to decide whether or not to ignore-list source files in a sourcemap, used to populate the x_google_ignoreList source map extension. relativeSourcePath is a relative path from the generated .map file to the corresponding source file while sourcemapPath is the fully resolved path of the generated sourcemap file.

js
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
		}
	]
};
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 以完全关闭忽略列表。

When you don't specify this option explicitly, by default it will put all files with node_modules in their path on the ignore list. You can specify false here to turn off the ignore-listing completely.

output.sourcemapPathTransform

类型:(relativeSourcePath: string, sourcemapPath: string) => string

应用于源映射中每个路径的转换。 relativeSourcePath 是从生成的 .map 文件到相应源文件的相对路径,而 sourcemapPath 是生成的源映射文件的完全解析路径。

A transformation to apply to each path in a sourcemap. relativeSourcePath is a relative path from the generated .map file to the corresponding source file while sourcemapPath is the fully resolved path of the generated sourcemap file.

js
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
		}
	]
};
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

类型:boolean
命令行接口:--validate/--no-validate
默认:false

重新解析每个生成的块以检测生成的代码是否是有效的 JavaScript。 这对于调试使用 renderChunk 钩子转换代码的插件生成的输出很有用。

Re-parses each generated chunk to detect if the generated code is valid JavaScript. This can be useful to debug output generated by plugins that use the renderChunk hook to transform code.

如果代码无效,将会触发警告。 请注意,不会引发任何错误,因此你仍然可以检查生成的输出。 要将此警告升级为错误,你可以在 onwarn 处理程序中监视它。

If the code is invalid, a warning will be issued. Note that no error is thrown so that you can still inspect the generated output. To promote this warning to an error, you can watch for it in an onwarn handler.

preserveEntrySignatures

类型:"strict" | "allow-extension" | "exports-only"| false
命令行接口:--preserveEntrySignatures <strict | allow-extension>/--no-preserveEntrySignatures
默认:"exports-only"

控制 Rollup 是否尝试确保条目块具有与底层条目模块相同的导出。

Controls if Rollup tries to ensure that entry chunks have the same exports as the underlying entry module.

  • 如果设置为 "strict",Rollup 将在条目块中创建与相应条目模块中完全相同的导出。 如果这是不可能的,因为需要将额外的内部导出添加到块中,则 Rollup 将创建一个 "正面" 条目块,该块仅从其他块重新导出必要的绑定,但不包含其他代码。 这是库的推荐设置。
  • "allow-extension" 将在入口块中创建入口模块的所有导出,但如果需要,也可能添加其他导出,以避免 "正面" 入口块。 此设置对于不需要严格签名的库有意义。
  • 如果入口模块具有导出,则 "exports-only" 的行为类似于 "strict",否则它的行为类似于 "allow-extension"
  • false 不会将入口模块的任何导出添加到相应的块中,甚至不包含相应的代码,除非这些导出在打包包中的其他地方使用。 不过,内部导出可以添加到条目块中。 对于将条目块放置在脚本标记中的 Web 应用,这是推荐的设置,因为它可能会减少块的数量,并可能减少包的大小。

例子
输入:

Example
Input:

js
// 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);
// 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" 的输出:

Output for preserveEntrySignatures: "strict":

js
// 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);
// 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" 的输出:

Output for preserveEntrySignatures: "allow-extension":

js
// 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);
// 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 的输出:

Output for preserveEntrySignatures: false:

js
// main.js
import('./dynamic-39821cef.js');

// dynamic-39821cef.js
const shared = 'shared';

console.log(shared);
// main.js
import('./dynamic-39821cef.js');

// dynamic-39821cef.js
const shared = 'shared';

console.log(shared);

目前,覆盖各个条目块的此设置的唯一方法是使用插件 API 并通过 this.emitFile 触发这些块,而不是使用 input 选项。

At the moment, the only way to override this setting for individual entry chunks is to use the plugin API and emit those chunks via this.emitFile instead of using the input option.

strictDeprecations

类型:boolean
命令行接口:--strictDeprecations/--no-strictDeprecations
默认:false

启用此标志后,在使用已弃用的功能时,Rollup 将引发错误,而不是显示警告。 此外,标记为在下一个主要版本中收到弃用警告的功能在使用时也会引发错误。

When this flag is enabled, Rollup will throw an error instead of showing a warning when a deprecated feature is used. Furthermore, features that are marked to receive a deprecation warning with the next major version will also throw an error when used.

该标志旨在由例如 插件作者能够尽早调整他们的插件以适应即将发布的主要版本。

This flag is intended to be used by e.g. plugin authors to be able to adjust their plugins for upcoming major releases as early as possible.

危险区

除非你知道自己在做什么,否则你可能不需要使用这些选项!

You probably don't need to use these options unless you know what you are doing!

context

类型:string
命令行接口:--context <contextVariable>
默认:undefined

默认情况下,模块的上下文 – 即顶层 this 的值 – 是 undefined。 在极少数情况下,你可能需要将其更改为其他内容,例如 'window'

By default, the context of a module – i.e., the value of this at the top level – is undefined. In rare cases you might need to change this to something else, like 'window'.

moduleContext

类型:((id: string) => string) | { [id: string]: string }

context 相同,但针对每个模块 – 可以是 id: context 对的对象,也可以是 id => context 函数。

Same as context, but per-module – can either be an object of id: context pairs, or an id => context function.

output.amd

类型:{ id?: string, autoId?: boolean, basePath?: string, define?: string }

注意 id 只能用于单文件构建,不能与 autoId/basePath 组合使用。

Note id can only be used for single-file builds, and cannot be combined with autoId/basePath.

output.amd.id

类型:string
命令行接口:--amd.id <amdId>

用于 AMD/UMD 打包包的 ID:

An ID to use for AMD/UMD bundles:

js
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    id: 'my-bundle'
  }
};

// -> define('my-bundle', ['dependency'], ...
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    id: 'my-bundle'
  }
};

// -> define('my-bundle', ['dependency'], ...

output.amd.autoId

类型:boolean
命令行接口:--amd.autoId

将 ID 设置为块 ID(删除 '.js' 扩展名)。

Set the ID to the chunk ID (with the '.js' extension removed).

js
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    autoId: true
  }
};

// -> define('main', ['dependency'], ...
// -> define('dynamic-chunk', ['dependency'], ...
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    autoId: true
  }
};

// -> define('main', ['dependency'], ...
// -> define('dynamic-chunk', ['dependency'], ...

output.amd.basePath

类型:string
命令行接口:--amd.basePath

将添加到自动生成的 ID 前面的路径。 如果构建将被放置在另一个 AMD 项目中并且不在根目录中,这非常有用。

The path that will be prepended to the auto generated ID. This is useful if the build is going to be placed inside another AMD project, and is not at the root.

仅对 output.amd.autoId 有效。

Only valid with output.amd.autoId.

js
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    autoId: true,
    basePath: 'some/where'
  }
};

// -> define('some/where/main', ['dependency'], ...
// -> define('some/where/dynamic-chunk', ['dependency'], ...
// 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
命令行接口:--amd.define <defineFunctionName>

用于代替 define 的函数名称:

A function name to use instead of define:

js
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    define: 'def'
  }
};

// -> def(['dependency'],...
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    define: 'def'
  }
};

// -> def(['dependency'],...

output.amd.forceJsExtensionForImports

类型:boolean
命令行接口:--amd.forceJsExtensionForImports
默认:false

添加 .js 扩展以导入生成的块和本地 AMD 模块:

Add .js extension for imports of generated chunks and local AMD modules:

js
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    forceJsExtensionForImports: true
  }
};

// -> define(['./chunk-or-local-file.js', 'dependency', 'third/dependency'],...
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    forceJsExtensionForImports: true
  }
};

// -> define(['./chunk-or-local-file.js', 'dependency', 'third/dependency'],...

output.esModule

类型:boolean | "if-default-prop"
命令行接口:--esModule/--no-esModule
默认:"if-default-prop"

生成非 ES 格式的导出时是否添加 __esModule: true 属性。 该属性表示导出的值是 ES 模块的命名空间,并且该模块的默认导出对应导出对象的 .default 属性。

Whether to add a __esModule: true property when generating exports for non-ES formats. This property signifies that the exported value is the namespace of an ES module and that the default export of this module corresponds to the .default property of the exported object.

  • true 在使用 命名导出模式 时总是会添加该属性,这与其他工具的做法类似。
  • "if-default-prop" 仅在使用命名导出模式时才会添加该属性,并且还有默认导出。 微妙的区别是,如果没有默认导出,CommonJS 版本的库的使用者将获得所有命名导出作为默认导出,而不是错误或 undefined。 我们选择将此设置为默认值,因为 __esModule 属性不是任何 JavaScript 运行时遵循的标准,并且会导致许多互操作问题,因此我们希望将其使用限制在真正需要的情况下。
  • 另一方面,false 永远不会添加该属性,即使默认导出将成为属性 .default

另见 output.interop

See also output.interop.

output.exports

类型:"auto" | "default"| "named"| "none"
命令行接口:--exports <exportMode>
默认:'auto'

使用什么导出模式。 默认为 auto,它根据 input 模块导出的内容猜测你的意图:

What export mode to use. Defaults to auto, which guesses your intentions based on what the input module exports:

  • default – 如果你只使用 export default ... 导出一件东西; 请注意,这可能会在生成可与 ESM 输出互换的 CommonJS 输出时导致问题,请参见下文
  • named – 如果你使用命名导出
  • none – 如果你不导出任何内容(例如你正在构建应用,而不是库)

由于这只是一个输出转换,因此如果默认导出是所有条目块的唯一导出,则只能选择 default。 同样,如果没有导出,则只能选择 none,否则 Rollup 会抛出错误。

As this is only an output transformation, you can only choose default if a default export is the only export for all entry chunks. Likewise, you can only choose none if there are no exports, otherwise Rollup will throw an error.

defaultnamed 之间的差异会影响其他人如何使用你的打包包。 如果你使用 default,CommonJS 用户可以执行此操作,例如:

The difference between default and named affects how other people can consume your bundle. If you use default, a CommonJS user could do this, for example:

js
// your-lib package entry
export default 'Hello world';

// a CommonJS consumer
/* require( "your-lib" ) returns "Hello World" */
const hello = require('your-lib');
// your-lib package entry
export default 'Hello world';

// a CommonJS consumer
/* require( "your-lib" ) returns "Hello World" */
const hello = require('your-lib');

对于 named,用户可以这样做:

With named, a user would do this instead:

js
// 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');
// 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 导出,则用户必须执行以下操作才能使用默认导出:

The wrinkle is that if you use named exports but also have a default export, a user would have to do something like this to use the default export:

js
// 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');
// 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 属性。

Note: There are some tools such as Babel, TypeScript, Webpack, and @rollup/plugin-commonjs that are capable of resolving a CommonJS require(...) call with an ES module. If you are generating CommonJS output that is meant to be interchangeable with ESM output for those tools, you should always use named export mode. The reason is that most of those tools will by default return the namespace of an ES module on require where the default export is the .default property.

换句话说,对于这些工具,你无法创建 const lib = require("your-lib") 产生与 import lib from "your-lib" 相同的包接口。 然而,对于命名导出模式,const {lib} = require("your-lib") 将等同于 import {lib} from "your-lib"

In other words for those tools, you cannot create a package interface where const lib = require("your-lib") yields the same as import lib from "your-lib". With named export mode however, const {lib} = require("your-lib") will be equivalent to import {lib} from "your-lib".

output.externalLiveBindings

类型:boolean
命令行接口:--externalLiveBindings/--no-externalLiveBindings
默认:true

当设置为 false 时,Rollup 将不会生成代码来支持外部导入的实时绑定,而是假设导出不会随时间变化。 这将使 Rollup 能够生成更优化的代码。 请注意,当存在涉及外部依赖的循环依赖时,这可能会导致问题。

When set to false, Rollup will not generate code to support live bindings for external imports but instead assume that exports do not change over time. This will enable Rollup to generate more optimized code. Note that this can cause issues when there are circular dependencies involving an external dependency.

这将避免 Rollup 在代码中生成 getter 的大多数情况,因此在许多情况下可用于使代码兼容 IE8。

This will avoid most cases where Rollup generates getters in the code and can therefore be used to make code IE8 compatible in many cases.

例子:

Example:

js
// 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;
// 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

类型:boolean
命令行接口:--freeze/--no-freeze
默认:true

是否向 Object.freeze() 命名空间导入动态访问的对象(即 import * as namespaceImportObject from...)。

Whether to Object.freeze() namespace import objects (i.e. import * as namespaceImportObject from...) that are accessed dynamically.

output.indent

类型:boolean | string
命令行接口:--indent/--no-indent
默认:true

要使用的缩进字符串,适用于需要缩进代码的格式(amdiifeumdsystem)。 也可以是 false(无缩进)或 true(默认 - 自动缩进)

The indent string to use, for formats that require code to be indented (amd, iife, umd, system). Can also be false (no indent), or true (the default – auto-indent)

js
// rollup.config.js
export default {
  ...,
  output: {
    ...,
    indent: false
  }
};
// rollup.config.js
export default {
  ...,
  output: {
    ...,
    indent: false
  }
};

output.noConflict

类型:boolean
命令行接口:--noConflict/--no-noConflict
默认:false

这将生成一个额外的 noConflict 导出到 UMD 包。 在 IIFE 场景中调用时,此方法将返回包导出,同时将相应的全局变量恢复为其之前的值。

This will generate an additional noConflict export to UMD bundles. When called in an IIFE scenario, this method will return the bundle exports while restoring the corresponding global variable to its previous value.

output.sanitizeFileName

类型:boolean | (string) => string
命令行接口:--sanitizeFileName/no-sanitizeFileName
默认:true

设置为 false 以禁用所有块名称清理(删除 \0?* 字符)。

Set to false to disable all chunk name sanitizations (removal of \0, ? and * characters).

或者设置为允许自定义块名称清理的函数。

Alternatively set to a function to allow custom chunk name sanitization.

output.strict

类型:boolean
命令行接口:--strict/--no-strict
默认:true

是否在生成的非 ES 包的顶部包含 'use strict' 编译指示。 严格来说,ES 模块始终处于严格模式,因此你不应该在没有充分理由的情况下禁用它。

Whether to include the 'use strict' pragma at the top of generated non-ES bundles. Strictly speaking, ES modules are always in strict mode, so you shouldn't disable this without good reason.

output.systemNullSetters

类型:boolean
命令行接口:--systemNullSetters/--no-systemNullSetters
默认:true

当输出 system 模块格式时,默认情况下,空 setter 函数将替换为 null 作为输出简化。 这与 v6.3.3 之前的 SystemJS 不兼容。 停用此选项可输出空函数,而不是较旧的 SystemJS 版本支持的函数。

When outputting the system module format, by default, empty setter functions are replaced with null as an output simplification. This is incompatible with SystemJS before v6.3.3. Deactivate this option to output empty functions instead that older SystemJS versions support.

类型:boolean
命令行接口:--preserveSymlinks
默认:false

当设置为 false 时,解析文件时遵循符号链接。 当设置为 true 时,符号链接将被视为文件位于链接所在位置,而不是被跟踪。 为了说明这一点,请考虑以下情况:

When set to false, symbolic links are followed when resolving a file. When set to true, instead of being followed, symbolic links are treated as if the file is where the link is. To illustrate, consider the following situation:

js
// /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';
// /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';

如果 preserveSymlinksfalse,则从 /main.js 创建的包将记录 "紧挨着原来的",因为它将使用符号链接文件的位置来解析其依赖。 但是,如果 preserveSymlinkstrue,它将记录 "在链接旁边",因为符号链接不会被解析。

If preserveSymlinks is false, then the bundle created from /main.js will log "next to original" as it will use the location of the symbolically linked file to resolve its dependencies. If preserveSymlinks is true, however, it will log "next to linked" as the symbolic link will not be resolved.

shimMissingExports

类型:boolean
命令行接口:--shimMissingExports/--no-shimMissingExports
默认:false

如果提供此选项,并且从未定义这些绑定的文件导入绑定,则打包不会失败。 相反,将为这些绑定创建值为 undefined 的新变量。

If this option is provided, bundling will not fail if bindings are imported from a file that does not define these bindings. Instead, new variables will be created for these bindings with the value undefined.

treeshake

类型:boolean | TreeshakingPreset | TreeshakingOptions
命令行接口:--treeshake/--no-treeshake
默认:true
typescript
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;
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;

是否应用 tree-shaking 并微调 tree-shaking 过程。 将此选项设置为 false 将生成更大的打包包,但可能会提高构建性能。 你还可以选择三个预设之一,如果添加新选项,这些预设将自动更新:

Whether to apply tree-shaking and to fine-tune the tree-shaking process. Setting this option to false will produce bigger bundles but may improve build performance. You may also choose one of three presets that will automatically be updated if new options are added:

如果你发现由摇树算法引起的错误,请提出问题! 将此选项设置为对象意味着启用树摇动并授予以下附加选项:

If you discover a bug caused by the tree-shaking algorithm, please file an issue! Setting this option to an object implies tree-shaking is enabled and grants the following additional options:

treeshake.annotations

类型:boolean
命令行接口:--treeshake.annotations/--no-treeshake.annotations
默认:true

如果是 false,则忽略注释中注释的提示:

If false, ignore hints from annotation in comments:

@__PURE__

包含 @__PURE__#__PURE__ 的注释将特定函数调用或构造函数调用标记为无副作用。 这意味着 Rollup 将进行树摇动,即删除调用,除非在某些未进行树摇动的代码中使用返回值。 这些注释需要紧接在调用调用之前才能生效。 以下代码将完全进行树摇动,除非该选项设置为 false,在这种情况下它将保持不变。

Comments containing @__PURE__ or #__PURE__ mark a specific function call or constructor invocation as side effect free. That means that Rollup will tree-shake i.e. remove the call unless the return value is used in some code that is not tree-shaken. These annotations need to immediately precede the call invocation to take effect. The following code will be completely tree-shaken unless this option is set to false, in which case it will remain unchanged.

javascript
/*@__PURE__*/ console.log('side-effect');

class Impure {
	constructor() {
		console.log('side-effect');
	}
}

/*@__PURE__ There may be additional text in the comment */ new Impure();
/*@__PURE__*/ console.log('side-effect');

class Impure {
	constructor() {
		console.log('side-effect');
	}
}

/*@__PURE__ There may be additional text in the comment */ new Impure();

如果这样的注释直接位于函数调用或构造函数调用之前,并且仅通过空格或注释与被调用者分隔,则该注释被认为是有效的。 唯一的例外是封装调用或调用的括号。

Such an annotation is considered valid if it directly precedes a function call or constructor invocation and is only separated from the callee by white-space or comments. The only exception are parentheses that wrap a call or invocation.

无效注释将被删除,并且 Rollup 会触发警告。 有效注释保留在代码中,除非它们的函数调用或构造函数调用也被删除。

Invalid annotations are removed and Rollup emits a warning. Valid annotations remain in the code unless their function call or constructor invocation is removed as well.

@__NO_SIDE_EFFECTS__

包含 @__NO_SIDE_EFFECTS__#__NO_SIDE_EFFECTS__ 的注释将函数声明本身标记为无副作用。 当函数被标记为没有副作用时,对该函数的所有调用都将被视为无副作用。 以下代码将完全进行树摇动,除非该选项设置为 false,在这种情况下它将保持不变。

Comments containing @__NO_SIDE_EFFECTS__ or #__NO_SIDE_EFFECTS__ mark a function declaration itself as side effect free. When a function has been marked as having no side effects, all calls to that function will be considered to be side effect free. The following code will be completely tree-shaken unless this option is set to false, in which case it will remain unchanged.

javascript
/*@__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
/*@__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

如果这样的注释直接位于函数声明或常量变量声明之前,其中第一个声明的变量是函数并且仅通过空格或注释与声明分隔开,则该注释被认为是有效的。

Such an annotation is considered valid if it directly precedes a function declaration or a constant variable declaration where the first declared variable is a function and is only separated from the declaration by white-space or comments.

无效注释将被删除,并且 Rollup 会触发警告。 有效的注释保留在代码中,除非它们的声明也被删除

Invalid annotations are removed and Rollup emits a warning. Valid annotations remain in the code unless their declaration is removed as well

treeshake.correctVarValueBeforeDeclaration

类型:boolean
命令行接口:--treeshake.correctVarValueBeforeDeclaration/--no-treeshake.correctVarValueBeforeDeclaration
默认:false

在某些边缘情况下,如果变量在其声明赋值之前被访问且未重新赋值,则 Rollup 可能会错误地假定该变量在整个程序中是常量,如下例所示。 然而,如果变量是用 var 声明的,则情况并非如此,因为这些变量可以在声明之前被访问,它们的计算结果将是 undefined。 选择 true 将确保 Rollup 不会对使用 var 声明的变量的值做出任何假设。 但请注意,这可能会对 tree-shaking 结果产生明显的负面影响。

In some edge cases if a variable is accessed before its declaration assignment and is not reassigned, then Rollup may incorrectly assume that variable is constant throughout the program, as in the example below. This is not true if the variable is declared with var, however, as those variables can be accessed before their declaration where they will evaluate to undefined. Choosing true will make sure Rollup does not make any assumptions about the value of variables declared with var. Note though that this can have a noticeable negative impact on tree-shaking results.

js
// 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
// 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[]
命令行接口:--treeshake.manualPureFunctions <names>

允许手动定义应始终被视为 "纯的" 的函数名称列表,即它们在调用时没有更改全局状态等副作用。 仅通过名称进行检查。

Allows to manually define a list of function names that should always be considered "pure", i.e. they have no side effects like changing global state etc. when called. The check is performed solely by name.

这不仅可以帮助删除死代码,还可以改善 JavaScript 块的生成,尤其是在使用 output.experimentalMinChunkSize 时。

This can not only help with dead code removal, but can also improve JavaScript chunk generation especially when using output.experimentalMinChunkSize.

除了与该名称匹配的任何函数之外,纯函数上的任何属性以及从纯函数返回的任何函数也将被视为纯函数,并且不会检查访问任何属性的副作用。

Besides any functions matching that name, any properties on a pure function and any functions returned from a pure functions will also be considered pure functions, and accessing any properties is not checked for side effects.

js
// 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
// 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
命令行接口:--treeshake.moduleSideEffects/--no-treeshake.moduleSideEffects/--treeshake.moduleSideEffects no-external
默认:true

如果是 false,则假设不导入任何内容的模块和外部依赖不会产生其他副作用,例如更改全局变量或在不检查的情况下进行日志记录。 对于外部依赖,这将抑制空导入:

If false, assume modules and external dependencies from which nothing is imported do not have other side effects like mutating global variables or logging without checking. For external dependencies, this will suppress empty imports:

javascript
// input file
import { unused } from 'external-a';
import 'external-b';
console.log(42);
// input file
import { unused } from 'external-a';
import 'external-b';
console.log(42);
javascript
// output with treeshake.moduleSideEffects === true
import 'external-a';
import 'external-b';
console.log(42);
// output with treeshake.moduleSideEffects === true
import 'external-a';
import 'external-b';
console.log(42);
javascript
// output with treeshake.moduleSideEffects === false
console.log(42);
// output with treeshake.moduleSideEffects === false
console.log(42);

对于非外部模块,false 将不包含来自模块的任何语句,除非至少包含来自该模块的一个导入:

For non-external modules, false will not include any statements from a module unless at least one import from this module is included:

javascript
// 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';
// 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';
javascript
// output with treeshake.moduleSideEffects === true
console.log('side-effect');

console.log(42);
// output with treeshake.moduleSideEffects === true
console.log('side-effect');

console.log(42);
javascript
// output with treeshake.moduleSideEffects === false
console.log(42);
// output with treeshake.moduleSideEffects === false
console.log(42);

你还可以提供具有副作用的模块列表或单独确定每个模块的副作用的函数。 值 "no-external" 将仅在可能的情况下删除外部导入,并且等同于函数 (id, external) => !external

You can also supply a list of modules with side effects or a function to determine it for each module individually. The value "no-external" will only remove external imports if possible and is equivalent to the function (id, external) => !external;

如果将此标志设置为 false 的模块从另一个模块重新导出变量并且使用此变量,则重新导出模块是否扫描副作用的问题取决于如何重新导出变量:

If a module that has this flag set to false reexports a variable from another module and this variable is used, the question if the reexporting module is scanned for side effects depends on how the variable is reexported:

javascript
// 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;
// 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;
javascript
// output with treeshake.moduleSideEffects === false
const foo = 42;

foo.mutated = true;
console.log('this side-effect and the mutation are retained');

console.log(foo);
// output with treeshake.moduleSideEffects === false
const foo = 42;

foo.mutated = true;
console.log('this side-effect and the mutation are retained');

console.log(foo);

请注意,尽管名称如此,此选项不会对没有副作用的模块产生 "添加" 副作用。 如果这很重要,例如 打包包中的空模块是 "包括",因为你需要它来进行依赖跟踪,插件接口允许你通过 resolveIdloadtransform 钩子将模块指定为从 tree-shaking 中排除。

Note that despite the name, this option does not "add" side effects to modules that do not have side effects. If it is important that e.g. an empty module is "included" in the bundle because you need this for dependency tracking, the plugin interface allows you to designate modules as being excluded from tree-shaking via the resolveId, load or transform hook.

treeshake.preset

类型:"smallest" | "safest"| "recommended"
命令行接口:--treeshake <value>

允许选择上面列出的预设之一,同时覆盖某些选项。

Allows choosing one of the presets listed above while overriding some options.

js
export default {
	treeshake: {
		preset: 'smallest',
		propertyReadSideEffects: true
	}
	// ...
};
export default {
	treeshake: {
		preset: 'smallest',
		propertyReadSideEffects: true
	}
	// ...
};

treeshake.propertyReadSideEffects

类型:boolean| 'always'
命令行接口:--treeshake.propertyReadSideEffects/--no-treeshake.propertyReadSideEffects
默认:true

如果 true,保留未使用的属性读取 Rollup 可以确定有副作用。 这包括访问 nullundefined 的属性或通过属性访问触发显式 getter。 请注意,这不包括作为函数参数传递的对象的解构赋值或 getter。

If true, retain unused property reads that Rollup can determine to have side effects. This includes accessing properties of null or undefined or triggering explicit getters via property access. Note that this does not cover destructuring assignment or getters on objects passed as function parameters.

如果是 false,则假设读取对象的属性不会产生副作用。 根据你的代码,禁用此选项可以显着减少包大小,但如果你依赖 getter 或来自非法属性访问的错误,则可能会破坏功能。

If false, assume reading a property of an object never has side effects. Depending on your code, disabling this option can significantly reduce bundle size but can potentially break functionality if you rely on getters or errors from illegal property access.

如果是 'always',则假设所有成员属性访问(包括解构)都有副作用。 对于依赖具有副作用的 getter 的代码,建议使用此设置。 它通常会导致更大的包大小,但小于完全禁用 treeshake

If 'always', assume all member property accesses, including destructuring, have side effects. This setting is recommended for code relying on getters with side effects. It typically results in larger bundle size, but smaller than disabling treeshake altogether.

javascript
// 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;
// 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

类型:boolean
命令行接口:--treeshake.tryCatchDeoptimization/--no-treeshake.tryCatchDeoptimization
默认:true

默认情况下,Rollup 假定运行时的许多内置全局变量在进行树摇动时按照最新规范运行,并且不会引发意外错误。 为了支持例如 依赖于抛出这些错误的功能检测工作流程,Rollup 默认情况下会停用 try 语句内的 tree-shaking。 如果从 try 语句内调用函数参数,则该参数也将被取消优化。 如果你不需要此功能并希望在 try 语句中进行树摇动,请将 treeshake.tryCatchDeoptimization 设置为 false

By default, Rollup assumes that many builtin globals of the runtime behave according to the latest specs when tree-shaking and do not throw unexpected errors. In order to support e.g. feature detection workflows that rely on those errors being thrown, Rollup will by default deactivate tree-shaking inside try-statements. If a function parameter is called from within a try-statement, this parameter will be deoptimized as well. Set treeshake.tryCatchDeoptimization to false if you do not need this feature and want to have tree-shaking inside try-statements.

js
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);
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

类型:boolean
命令行接口:--treeshake.unknownGlobalSideEffects/--no-treeshake.unknownGlobalSideEffects
默认:true

由于访问不存在的全局变量会引发错误,因此 Rollup 默认情况下会保留对非内置全局变量的任何访问。 将此选项设置为 false 以避免此检查。 这对于大多数代码库来说可能是安全的。

Since accessing a non-existing global variable will throw an error, Rollup does by default retain any accesses to non-builtin global variables. Set this option to false to avoid this check. This is probably safe for most code-bases.

js
// 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;
// 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;

在示例中,最后一行始终保留,因为如果 angular 是,则访问 element 属性也可能引发错误 null。 要避免此检查,请将 treeshake.propertyReadSideEffects 也设置为 false

In the example, the last line is always retained as accessing the element property could also throw an error if angular is e.g. null. To avoid this check, set treeshake.propertyReadSideEffects to false as well.

实验选项

这些选项反映了尚未完全确定的新功能。 因此,可用性、行为和使用可能会在次要版本之间发生变化。

These options reflect new features that have not yet been fully finalized. Availability, behaviour and usage may therefore be subject to change between minor versions.

experimentalCacheExpiry

类型:number
命令行接口:--experimentalCacheExpiry <numberOfRuns>
默认:10

确定运行多少次后应删除插件不再使用的缓存资源。

Determines after how many runs cached assets that are no longer used by plugins should be removed.

experimentalLogSideEffects

类型:boolean
命令行接口:--experimentalLogSideEffects/--no-experimentalLogSideEffects
默认:false

当设置为 true 时,这会将在每个文件中找到的第一个副作用记录到控制台。 这对于确定哪些文件有副作用以及实际的副作用是什么非常有帮助。 消除副作用可以改善 tree-shaking 和块生成,对于 output.experimentalMinChunkSize 的工作至关重要。

When set to true, this will log the first side effect it finds in every file to the console. This can be very helpful to figure which files have side effects and what the actual side effects are. Removing side effects can improve tree-shaking and chunk generation and is crucial to make output.experimentalMinChunkSize work.

不过,此选项只会记录顶层语句。 有时,例如 在立即调用函数表达式的情况下,实际的副作用可以隐藏在嵌套表达式内。

This option will only log top-level statements, though. Sometimes, e.g. in case of immediately-invoked-function-expressions, the actual side effect can be hidden inside a nested expression.

output.experimentalMinChunkSize

类型:number
命令行接口:--experimentalMinChunkSize <size>
默认:1

设置代码分割设置的最小块大小目标(以字节为单位)。 当该值设置为默认值 1 时,Rollup 将尝试将除导入和重新导出之外不包含代码的块合并到其他块中。 仅当合并不会改变加载任何条目时执行的副作用时,才会执行合并。 对于 1 的值,仅允许合并,且不会增加任何条目加载的代码量。

Set a minimal chunk size target in Byte for code-splitting setups. When this value is set to the default of 1, Rollup will try to merge chunks that do not contain code except imports and reexports into other chunks. A merge will only be performed if it does not change what side effects are executed when any entry is loaded. For the value of 1, only merges are permitted that do no increase the amount of code loaded for any entry.

较大的值将尝试将低于限制的任何块合并到其他块中。 在这种情况下,条目可能会加载一些不必要的代码,这是可以接受的。 不过,该算法始终尝试以最小化不必要代码量的方式进行合并。

Larger values will try to merge any chunk below the limit into other chunks. In that case, it is accepted that entries may load some unnecessary code. The algorithm always tries to merge in a way that minimizes the amount of unnecessary code, though.

不幸的是,由于分块的工作方式,块大小是在任何块渲染插件(如缩小器)运行之前测量的,这意味着你应该使用足够高的限制来考虑这一点。 不过,在计算大小时,它将考虑顶层语句的树摇动。

Unfortunately, due to the way chunking works, chunk size is measured before any chunk rendering plugins like minifiers ran, which means you should use a high enough limit to take this into account. When calculating the size, it will take tree-shaking of top-level statements into account, though.

perf

类型:boolean
命令行接口:--perf/--no-perf
默认:false

是否收集性能计时。 当从命令行或配置文件使用时,将显示有关当前打包过程的详细测量结果。 当从 JavaScript API 使用时,返回的打包对象将包含一个附加的 getTimings() 函数,可以随时调用该函数来检索所有累积的测量值。

Whether to collect performance timings. When used from the command line or a configuration file, detailed measurements about the current bundling process will be displayed. When used from the JavaScript API, the returned bundle object will contain an additional getTimings() function that can be called at any time to retrieve all accumulated measurements.

getTimings() 返回以下形式的对象:

getTimings() returns an object of the following form:

{
  "# BUILD": [ 698.020877, 33979632, 45328080 ],
  "## parse modules": [ 537.509342, 16295024, 27660296 ],
  "load modules": [ 33.253778999999994, 2277104, 38204152 ],
  ...
}
{
  "# BUILD": [ 698.020877, 33979632, 45328080 ],
  "## parse modules": [ 537.509342, 16295024, 27660296 ],
  "load modules": [ 33.253778999999994, 2277104, 38204152 ],
  ...
}

对于每个键,第一个数字表示经过的时间,第二个数字表示内存消耗的变化,第三个数字表示此步骤后的总内存消耗。 这些步骤的顺序是 Object.keys 使用的顺序。 顶层键以 # 开始,包含嵌套步骤的计时,即在上面的示例中,# BUILD 步骤的 698 毫秒包括 ## parse modules 步骤的 538 毫秒。

For each key, the first number represents the elapsed time while the second represents the change in memory consumption, and the third represents the total memory consumption after this step. The order of these steps is the order used by Object.keys. Top level keys start with # and contain the timings of nested steps, i.e. in the example above, the 698ms of the # BUILD step include the 538ms of the ## parse modules step.

监视

类型:WatcherOptions | false
默认:{}
typescript
interface WatcherOptions {
	buildDelay?: number;
	chokidar?: ChokidarOptions;
	clearScreen?: boolean;
	exclude?: string | RegExp | (string | RegExp)[];
	include?: string | RegExp | (string | RegExp)[];
	skipWrite?: boolean;
}
interface WatcherOptions {
	buildDelay?: number;
	chokidar?: ChokidarOptions;
	clearScreen?: boolean;
	exclude?: string | RegExp | (string | RegExp)[];
	include?: string | RegExp | (string | RegExp)[];
	skipWrite?: boolean;
}

指定监视模式选项或阻止监视此配置。 仅当使用配置数组时,指定 false 才真正有用。 在这种情况下,此配置不会在监视模式更改时构建或重建,但会在定期运行 Rollup 时构建:

Specify options for watch mode or prevent this configuration from being watched. Specifying false is only really useful when an array of configurations is used. In that case, this configuration will not be built or rebuilt on change in watch mode, but it will be built when running Rollup regularly:

js
// 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' }
	}
];
// 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.watch 运行 Rollup 时生效。

These options only take effect when running Rollup with the --watch flag, or using rollup.watch.

watch.buildDelay

类型:number
命令行接口:--watch.buildDelay <number>
默认:0

配置 Rollup 将等待进一步更改直到触发重建(以毫秒为单位)的时间。 默认情况下,Rollup 不会等待,但在 chokidar 实例中配置了一个小的反跳超时。 将其设置为大于 0 的值意味着 Rollup 仅在配置的毫秒数没有更改的情况下才会触发重建。 如果观察多个配置,Rollup 将使用最大配置的构建延迟。

Configures how long Rollup will wait for further changes until it triggers a rebuild in milliseconds. By default, Rollup does not wait but there is a small debounce timeout configured in the chokidar instance. Setting this to a value greater than 0 will mean that Rollup will only trigger a rebuild if there was no change for the configured number of milliseconds. If several configurations are watched, Rollup will use the largest configured build delay.

watch.chokidar

类型:ChokidarOptions

将传递给打包的 乔基达尔 实例的监视选项的可选对象。 请参阅 乔基达尔文档 以了解可用的选项。

An optional object of watch options that will be passed to the bundled chokidar instance. See the chokidar documentation to find out what options are available.

watch.clearScreen

类型:boolean
命令行接口:--watch.clearScreen/--no-watch.clearScreen
默认:true

触发重建时是否清除屏幕。

Whether to clear the screen when a rebuild is triggered.

watch.exclude

类型:string | RegExp| (string| RegExp)[]
命令行接口:--watch.exclude <files>

防止文件被监视:

Prevent files from being watched:

js
// rollup.config.js
export default {
  ...,
  watch: {
    exclude: 'node_modules/**'
  }
};
// rollup.config.js
export default {
  ...,
  watch: {
    exclude: 'node_modules/**'
  }
};

watch.include

类型:string | RegExp| (string| RegExp)[]
命令行接口:--watch.include <files>

将文件监视限制为某些文件。 请注意,这仅过滤模块图,但不允许添加额外的监视文件:

Limit the file-watching to certain files. Note that this only filters the module graph but does not allow adding additional watch files:

js
// rollup.config.js
export default {
  ...,
  watch: {
    include: 'src/**'
  }
};
// rollup.config.js
export default {
  ...,
  watch: {
    include: 'src/**'
  }
};

watch.skipWrite

类型:boolean
命令行接口:--watch.skipWrite/--no-watch.skipWrite
默认:false

触发重建时是否跳过 bundle.write() 步骤。

Whether to skip the bundle.write() step when a rebuild is triggered.

已弃用的选项

☢️ 这些选项已被弃用,并且可能会在未来的 Rollup 版本中删除。

☢️ These options have been deprecated and may be removed in a future Rollup version.

output.externalImportAssertions

请改用 output.externalImportAttributes 选项。

Use the output.externalImportAttributes option instead.

类型:boolean
命令行接口:--externalImportAssertions/--no-externalImportAssertions
默认:true

如果输出格式为 es,是否在输出中向外部导入添加导入断言。 默认情况下,断言是从输入文件中获取的,但插件可以稍后添加或删除断言。 例如。 除非该选项设置为 false,否则 import "foo" assert {type: "json"} 将导致相同的导入出现在输出中。 请注意,模块的所有导入都需要具有一致的断言,否则会触发警告。

Whether to add import assertions to external imports in the output if the output format is es. By default, assertions are taken from the input files, but plugins can add or remove assertions later. E.g. import "foo" assert {type: "json"} will cause the same import to appear in the output unless the option is set to false. Note that all imports of a module need to have consistent assertions, otherwise a warning is emitted.