跳至内容

命令行界面

Rollup 通常应该从命令行使用。您可以提供一个可选的 Rollup 配置文件来简化命令行使用并启用高级 Rollup 功能。

配置文件

Rollup 配置文件是可选的,但它们功能强大且方便,因此**建议**使用。配置文件是一个 ES 模块,它导出一个包含所需选项的默认对象

javascript
export default {
	input: 'src/main.js',
	output: {
		file: 'bundle.js',
		format: 'cjs'
	}
};

通常,它被称为 rollup.config.jsrollup.config.mjs,位于项目根目录中。除非使用 --configPlugin--bundleConfigAsCjs 选项,否则 Rollup 将直接使用 Node 导入该文件。请注意,使用原生 Node ES 模块时存在一些注意事项,因为 Rollup 将遵循Node ESM 语义

如果您想使用 requiremodule.exports 将您的配置编写为 CommonJS 模块,您应该将文件扩展名更改为 .cjs

您还可以使用其他语言(如 TypeScript)来编写配置文件。为此,请安装相应的 Rollup 插件(如 @rollup/plugin-typescript)并使用 --configPlugin 选项

shell
rollup --config rollup.config.ts --configPlugin typescript

使用 --configPlugin 选项将始终强制您的配置文件首先被转译为 CommonJS。此外,请查看 配置智能提示,了解在配置文件中使用 TypeScript 类型定义的更多方法。

配置文件支持下面列出的选项。有关每个选项的详细信息,请参阅 选项列表

javascript
// rollup.config.js

// can be an array (for multiple inputs)
export default {
	// core input options
	external,
	input, // conditionally required
	plugins,

	// advanced input options
	cache,
	logLevel,
	makeAbsoluteExternalsRelative,
	maxParallelFileOps,
	onLog,
	onwarn,
	preserveEntrySignatures,
	strictDeprecations,

	// danger zone
	context,
	moduleContext,
	preserveSymlinks,
	shimMissingExports,
	treeshake,

	// experimental
	experimentalCacheExpiry,
	experimentalLogSideEffects,
	experimentalMinChunkSize,
	perf,

	// required (can be an array, for multiple outputs)
	output: {
		// core output options
		dir,
		file,
		format,
		globals,
		name,
		plugins,

		// advanced output options
		assetFileNames,
		banner,
		chunkFileNames,
		compact,
		dynamicImportInCjs,
		entryFileNames,
		extend,
		externalImportAttributes,
		footer,
		generatedCode,
		hashCharacters,
		hoistTransitiveImports,
		inlineDynamicImports,
		interop,
		intro,
		manualChunks,
		minifyInternalExports,
		outro,
		paths,
		preserveModules,
		preserveModulesRoot,
		sourcemap,
		sourcemapBaseUrl,
		sourcemapExcludeSources,
		sourcemapFile,
		sourcemapFileNames,
		sourcemapIgnoreList,
		sourcemapPathTransform,
		validate,

		// danger zone
		amd,
		esModule,
		exports,
		externalLiveBindings,
		freeze,
		indent,
		noConflict,
		sanitizeFileName,
		strict,
		systemNullSetters,

		// experimental
		experimentalMinChunkSize
	},

	watch: {
		buildDelay,
		chokidar,
		clearScreen,
		exclude,
		include,
		skipWrite
	}
};

您可以从配置文件中导出一个**数组**,以便一次从多个不相关的输入构建捆绑包,即使在监视模式下也是如此。要使用相同的输入构建不同的捆绑包,您需要为每个输入提供一个输出选项数组

javascript
// rollup.config.js (building more than one bundle)

export default [
	{
		input: 'main-a.js',
		output: {
			file: 'dist/bundle-a.js',
			format: 'cjs'
		}
	},
	{
		input: 'main-b.js',
		output: [
			{
				file: 'dist/bundle-b1.js',
				format: 'cjs'
			},
			{
				file: 'dist/bundle-b2.js',
				format: 'es'
			}
		]
	}
];

如果您想异步创建配置,Rollup 也可以处理一个解析为对象或数组的 Promise

javascript
// rollup.config.js
import fetch from 'node-fetch';

export default fetch('/some-remote-service-which-returns-actual-config');

同样,您也可以这样做

javascript
// rollup.config.js (Promise resolving an array)
export default Promise.all([fetch('get-config-1'), fetch('get-config-2')]);

要将 Rollup 与配置文件一起使用,请传递 --config-c 标志

shell
# pass a custom config file location to Rollup
rollup --config my.config.js

# if you do not pass a file name, Rollup will try to load
# configuration files in the following order:
# rollup.config.mjs -> rollup.config.cjs -> rollup.config.js
rollup --config

您还可以导出一个返回上述任何配置格式的函数。此函数将传递当前命令行参数,以便您可以动态调整配置以尊重例如 --silent。如果您在它们前面加上 config,您甚至可以定义自己的命令行选项

javascript
// rollup.config.js
import defaultConfig from './rollup.default.config.js';
import debugConfig from './rollup.debug.config.js';

export default commandLineArgs => {
	if (commandLineArgs.configDebug === true) {
		return debugConfig;
	}
	return defaultConfig;
};

如果您现在运行 rollup --config --configDebug,将使用调试配置。

默认情况下,命令行参数将始终覆盖从配置文件导出的相应值。如果您想更改此行为,您可以通过从 commandLineArgs 对象中删除它们来使 Rollup 忽略命令行参数

javascript
// rollup.config.js
export default commandLineArgs => {
  const inputBase = commandLineArgs.input || 'main.js';

  // this will make Rollup ignore the CLI argument
  delete commandLineArgs.input;
  return {
    input: 'src/entries/' + inputBase,
    output: { ... }
  }
}

配置智能提示

由于 Rollup 附带 TypeScript 类型定义,因此您可以利用 IDE 的智能提示和 JSDoc 类型提示

javascript
// rollup.config.js
/**
 * @type {import('rollup').RollupOptions}
 */
const config = {
	/* your config */
};
export default config;

或者,您可以使用 defineConfig 帮助程序,它应该提供智能提示,而无需 JSDoc 注释

javascript
// rollup.config.js
import { defineConfig } from 'rollup';

export default defineConfig({
	/* your config */
});

除了 RollupOptions 和封装此类型的 defineConfig 帮助程序之外,以下类型也可能有用

  • OutputOptions:配置文件的 output 部分
  • Plugin:提供 name 和一些钩子的插件对象。所有钩子都经过完全类型化以帮助插件开发。
  • PluginImpl:一个函数,它将选项对象映射到插件对象。大多数公共 Rollup 插件都遵循这种模式。

您还可以通过 --configPlugin 选项直接在 TypeScript 中编写配置。使用 TypeScript,您可以直接导入 RollupOptions 类型

typescript
import type { RollupOptions } from 'rollup';

const config: RollupOptions = {
	/* your config */
};
export default config;

与 JavaScript API 的区别

虽然配置文件提供了一种配置 Rollup 的简单方法,但它们也限制了 Rollup 的调用和配置方式。特别是如果您将 Rollup 捆绑到另一个构建工具中,或者想将其集成到高级构建流程中,那么直接从脚本以编程方式调用 Rollup 可能更好。

如果您想在某个时候从配置文件切换到使用 JavaScript API,则需要注意一些重要的区别

  • 使用 JavaScript API 时,传递给 rollup.rollup 的配置必须是一个对象,不能包装在 Promise 或函数中。
  • 您不能再使用配置数组。相反,您应该为每组 inputOptions 运行一次 rollup.rollup
  • output 选项将被忽略。相反,您应该为每组 outputOptions 运行一次 bundle.generate(outputOptions)bundle.write(outputOptions)

从 Node 包加载配置

为了互操作性,Rollup 还支持从安装到 node_modules 的包中加载配置文件

shell
# this will first try to load the package "rollup-config-my-special-config";
# if that fails, it will then try to load "my-special-config"
rollup --config node:my-special-config

使用原生 Node ES 模块时的注意事项

特别是在从旧版 Rollup 版本升级时,使用原生 ES 模块作为配置文件时,您需要注意一些事项。

获取当前目录

对于 CommonJS 文件,人们经常使用 __dirname 来访问当前目录并将相对路径解析为绝对路径。这对于原生 ES 模块不受支持。相反,我们建议使用以下方法,例如为外部模块生成绝对 ID

js
// rollup.config.js
import { fileURLToPath } from 'node:url'

export default {
  ...,
  // generates an absolute path for <currentdir>/src/some-file.js
  external: [fileURLToPath(new URL('src/some-file.js', import.meta.url))]
};

导入 package.json

导入包文件可能很有用,例如自动将您的依赖项标记为“外部”。根据您的 Node 版本,有不同的方法可以做到这一点

  • 对于 Node 17.5+,您可以使用导入断言

    js
    import pkg from './package.json' assert { type: 'json' };
    
    export default {
    	// Mark package dependencies as "external". Rest of configuration
    	// omitted.
    	external: Object.keys(pkg.dependencies)
    };
  • 对于旧版 Node 版本,您可以使用 createRequire

    js
    import { createRequire } from 'node:module';
    const require = createRequire(import.meta.url);
    const pkg = require('./package.json');
    
    // ...
  • 或者直接从磁盘读取和解析文件

    js
    // rollup.config.mjs
    import { readFileSync } from 'node:fs';
    
    // Use import.meta.url to make the path relative to the current source
    // file instead of process.cwd(). For more information:
    // https://node.org.cn/docs/latest-v16.x/api/esm.html#importmetaurl
    const packageJson = JSON.parse(
    	readFileSync(new URL('./package.json', import.meta.url))
    );
    
    // ...

命令行标志

许多选项都有命令行等效项。在这些情况下,任何在此处传递的参数都将覆盖配置文件(如果您使用的是配置文件)。这是所有支持选项的列表

-c, --config <filename>     Use this config file (if argument is used but value
                              is unspecified, defaults to rollup.config.js)
-d, --dir <dirname>         Directory for chunks (if absent, prints to stdout)
-e, --external <ids>        Comma-separate list of module IDs to exclude
-f, --format <format>       Type of output (amd, cjs, es, iife, umd, system)
-g, --globals <pairs>       Comma-separate list of `moduleID:Global` pairs
-h, --help                  Show this help message
-i, --input <filename>      Input (alternative to <entry file>)
-m, --sourcemap             Generate sourcemap (`-m inline` for inline map)
-n, --name <name>           Name for UMD export
-o, --file <output>         Single output file (if absent, prints to stdout)
-p, --plugin <plugin>       Use the plugin specified (may be repeated)
-v, --version               Show version number
-w, --watch                 Watch files in bundle and rebuild on changes
--amd.autoId                Generate the AMD ID based off the chunk name
--amd.basePath <prefix>     Path to prepend to auto generated AMD ID
--amd.define <name>         Function to use in place of `define`
--amd.forceJsExtensionForImports Use `.js` extension in AMD imports
--amd.id <id>               ID for AMD module (default is anonymous)
--assetFileNames <pattern>  Name pattern for emitted assets
--banner <text>             Code to insert at top of bundle (outside wrapper)
--chunkFileNames <pattern>  Name pattern for emitted secondary chunks
--compact                   Minify wrapper code
--context <variable>        Specify top-level `this` value
--no-dynamicImportInCjs     Write external dynamic CommonJS imports as require
--entryFileNames <pattern>  Name pattern for emitted entry chunks
--environment <values>      Settings passed to config file (see example)
--no-esModule               Do not add __esModule property
--exports <mode>            Specify export mode (auto, default, named, none)
--extend                    Extend global variable defined by --name
--no-externalImportAttributes Omit import attributes in "es" output
--no-externalLiveBindings   Do not generate code to support live bindings
--failAfterWarnings         Exit with an error if the build produced warnings
--filterLogs <filter>       Filter log messages
--footer <text>             Code to insert at end of bundle (outside wrapper)
--forceExit                 Force exit the process when done
--no-freeze                 Do not freeze namespace objects
--generatedCode <preset>    Which code features to use (es5/es2015)
--generatedCode.arrowFunctions Use arrow functions in generated code
--generatedCode.constBindings Use "const" in generated code
--generatedCode.objectShorthand Use shorthand properties in generated code
--no-generatedCode.reservedNamesAsProps Always quote reserved names as props
--generatedCode.symbols     Use symbols in generated code
--hashCharacters <name>     Use the specified character set for file hashes
--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks
--no-indent                 Don't indent result
--inlineDynamicImports      Create single bundle when using dynamic imports
--no-interop                Do not include interop block
--intro <text>              Code to insert at top of bundle (inside wrapper)
--logLevel <level>          Which kind of logs to display
--no-makeAbsoluteExternalsRelative Prevent normalization of external imports
--maxParallelFileOps <value> How many files to read in parallel
--minifyInternalExports     Force or disable minification of internal exports
--noConflict                Generate a noConflict method for UMD globals
--outro <text>              Code to insert at end of bundle (inside wrapper)
--perf                      Display performance timings
--no-preserveEntrySignatures Avoid facade chunks for entry points
--preserveModules           Preserve module structure
--preserveModulesRoot       Put preserved modules under this path at root level
--preserveSymlinks          Do not follow symlinks when resolving files
--no-reexportProtoFromExternal Ignore `__proto__` in star re-exports
--no-sanitizeFileName       Do not replace invalid characters in file names
--shimMissingExports        Create shim variables for missing exports
--silent                    Don't print warnings
--sourcemapBaseUrl <url>    Emit absolute sourcemap URLs with given base
--sourcemapExcludeSources   Do not include source code in source maps
--sourcemapFile <file>      Specify bundle position for source maps
--sourcemapFileNames <pattern> Name pattern for emitted sourcemaps
--stdin=ext                 Specify file extension used for stdin input
--no-stdin                  Do not read "-" from stdin
--no-strict                 Don't emit `"use strict";` in the generated modules
--strictDeprecations        Throw errors for deprecated features
--no-systemNullSetters      Do not replace empty SystemJS setters with `null`
--no-treeshake              Disable tree-shaking optimisations
--no-treeshake.annotations  Ignore pure call annotations
--treeshake.correctVarValueBeforeDeclaration Deoptimize variables until declared
--treeshake.manualPureFunctions <names> Manually declare functions as pure
--no-treeshake.moduleSideEffects Assume modules have no side effects
--no-treeshake.propertyReadSideEffects Ignore property access side effects
--no-treeshake.tryCatchDeoptimization Do not turn off try-catch-tree-shaking
--no-treeshake.unknownGlobalSideEffects Assume unknown globals do not throw
--validate                  Validate output
--waitForBundleInput        Wait for bundle input files
--watch.buildDelay <number> Throttle watch rebuilds
--no-watch.clearScreen      Do not clear the screen when rebuilding
--watch.exclude <files>     Exclude files from being watched
--watch.include <files>     Limit watching to specified files
--watch.onBundleEnd <cmd>   Shell command to run on `"BUNDLE_END"` event
--watch.onBundleStart <cmd> Shell command to run on `"BUNDLE_START"` event
--watch.onEnd <cmd>         Shell command to run on `"END"` event
--watch.onError <cmd>       Shell command to run on `"ERROR"` event
--watch.onStart <cmd>       Shell command to run on `"START"` event
--watch.skipWrite           Do not write files to disk when watching

下面列出的标志只能通过命令行界面使用。所有其他标志都对应于并覆盖其配置文件等效项,有关详细信息,请参阅 选项列表

--bundleConfigAsCjs

此选项将强制您的配置被转译为 CommonJS。

这允许您在配置中使用 CommonJS 习惯用法(如 __dirnamerequire.resolve),即使配置本身是作为 ES 模块编写的。

--configPlugin <plugin>

允许指定 Rollup 插件来转译或以其他方式控制配置文件的解析。主要好处是它允许您使用非 JavaScript 配置文件。例如,以下操作将允许您使用 TypeScript 编写配置,前提是您已安装 @rollup/plugin-typescript

shell
rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript

注意:对于 Typescript,请确保您的 tsconfig.jsoninclude 路径中包含 Rollup 配置文件。例如

"include": ["src/**/*", "rollup.config.ts"],

此选项支持与 --plugin 选项相同的语法,即您可以多次指定选项,可以省略 @rollup/plugin- 前缀并只写 typescript,并且可以通过 ={...} 指定插件选项。

使用此选项将使 Rollup 首先将您的配置文件转译为 ES 模块,然后再执行它。要改为转译为 CommonJS,请同时传递 --bundleConfigAsCjs 选项。

--environment <values>

通过 process.ENV 将其他设置传递给配置文件。

shell
rollup -c --environment INCLUDE_DEPS,BUILD:production

将设置 process.env.INCLUDE_DEPS === 'true'process.env.BUILD === 'production'。您可以多次使用此选项。在这种情况下,随后设置的变量将覆盖之前的定义。这使您能够例如覆盖 package.json 脚本中的环境变量

json
{
	"scripts": {
		"build": "rollup -c --environment INCLUDE_DEPS,BUILD:production"
	}
}

如果您通过以下方式调用此脚本

shell
npm run build -- --environment BUILD:development

那么配置文件将接收 process.env.INCLUDE_DEPS === 'true'process.env.BUILD === 'development'

--failAfterWarnings

如果在构建完成后出现任何警告,则退出构建并显示错误。

--filterLogs <filter>

仅根据自定义过滤器显示某些日志消息。在最基本的形式中,过滤器是一个 key:value 对,其中键是日志对象的属性,值是允许的值。例如

shell
rollup -c --filterLogs code:EVAL

将仅显示 log.code === 'EVAL' 的日志消息。您可以通过用逗号分隔它们或多次使用选项来指定多个过滤器

shell
rollup -c --filterLogs "code:FOO,message:This is the message" --filterLogs code:BAR

这将显示所有 code"FOO""BAR"message"This is the message" 的日志。

对于无法轻松添加其他命令行参数的情况,您还可以使用 ROLLUP_FILTER_LOGS 环境变量。此变量的值将与您在命令行上指定 --filterLogs 的方式相同,并支持用逗号分隔的过滤器列表。

还有一些高级语法可用于更复杂的过滤器。

  • ! 将否定过滤器

    shell
    rollup -c --filterLogs "!code:CIRCULAR_DEPENDENCY"

    将显示除循环依赖警告之外的所有日志。

  • * 在过滤器值中使用时匹配任何子字符串

    shell
    rollup -c --filterLogs "code:*_ERROR,message:*error*"

    将仅显示 code_ERROR 结尾或 message 包含字符串 error 的日志。

  • & 交叉多个过滤器

    shell
    rollup -c --filterLogs "code:CIRCULAR_DEPENDENCY&ids:*/main.js*"

    仅显示同时满足以下条件的日志:code"CIRCULAR_DEPENDENCY"ids 包含 /main.js。这利用了另一个功能

  • 如果值为对象,则在应用过滤器之前,它将通过 JSON.stringify 转换为字符串。其他非字符串值将直接转换为字符串。

  • 也支持嵌套属性

    shell
    rollup -c --filterLogs "foo.bar:value"

    仅显示属性 log.foo.bar 的值为 "value" 的日志。

--forceExit

完成时强制退出进程。在某些情况下,插件或其依赖项可能无法正确清理,并阻止 CLI 进程退出。根本原因可能难以诊断,此标志提供了一个逃生舱口,直到可以识别并解决它为止。

请注意,这可能会破坏某些工作流程,并且不会始终正常工作。

-h/--help

打印帮助文档。

-p <plugin>, --plugin <plugin>

使用指定的插件。这里有几种指定插件的方法

  • 通过相对路径

    shell
    rollup -i input.js -f es -p ./my-plugin.js

    该文件应导出一个返回插件对象的函数。

  • 通过安装在本地或全局 node_modules 文件夹中的插件的名称

    shell
    rollup -i input.js -f es -p @rollup/plugin-node-resolve

    如果插件名称不以 rollup-plugin-@rollup/plugin- 开头,Rollup 将自动尝试添加这些前缀

    shell
    rollup -i input.js -f es -p node-resolve
  • 通过内联实现

    shell
    rollup -i input.js -f es -p '{transform: (c, i) => `/* ${JSON.stringify(i)} */\n${c}`}'

如果要加载多个插件,可以重复选项或提供以逗号分隔的名称列表

shell
rollup -i input.js -f es -p node-resolve -p commonjs,json

默认情况下,插件函数将使用无参数调用以创建插件。但是,您也可以传递自定义参数

shell
rollup -i input.js -f es -p 'terser={output: {beautify: true, indent_level: 2}}'

--silent

不要将警告打印到控制台。如果您的配置文件包含 onLogonwarn 处理程序,则此处理程序仍将被调用。对于具有 onLog 钩子的插件也是如此。要防止这种情况,请另外使用 logLevel 选项或传递 --logLevel silent

--stdin=ext

从 stdin 读取内容时指定虚拟文件扩展名。默认情况下,Rollup 将使用虚拟文件名 - 而不带扩展名来表示从 stdin 读取的内容。但是,某些插件依赖于文件扩展名来确定它们是否应该处理文件。另请参见 从 stdin 读取文件

--no-stdin

不要从 stdin 读取文件。设置此标志将阻止将内容管道传输到 Rollup,并确保 Rollup 将 --.[ext] 解释为常规文件名,而不是将它们解释为 stdin 的名称。另请参见 从 stdin 读取文件

-v/--version

打印安装的版本号。

--waitForBundleInput

如果其中一个入口点文件不可用,这将不会抛出错误。相反,它将等待所有文件都存在,然后再开始构建。这很有用,尤其是在监视模式下,当 Rollup 正在使用另一个进程的输出时。

-w/--watch

当其源文件在磁盘上更改时重新构建捆绑包。

注意:在监视模式下,ROLLUP_WATCH 环境变量将由 Rollup 的命令行界面设置为 "true",并且可以由其他进程检查。插件应改为检查 this.meta.watchMode,它独立于命令行界面。

--watch.onStart <cmd>, --watch.onBundleStart <cmd>, --watch.onBundleEnd <cmd>, --watch.onEnd <cmd>, --watch.onError <cmd>

在监视模式下,为监视事件代码运行 shell 命令 <cmd>。另请参见 rollup.watch

shell
rollup -c --watch --watch.onEnd="node ./afterBuildScript.js"

从 stdin 读取文件

使用命令行界面时,Rollup 也可以从 stdin 读取内容

shell
echo "export const foo = 42;" | rollup --format cjs --file out.js

当此文件包含导入时,Rollup 将尝试相对于当前工作目录解析它们。使用配置文件时,Rollup 仅在入口点文件的名称为 - 时才使用 stdin 作为入口点。要从 stdin 读取非入口点文件,只需将其称为 -,这是在内部用于引用 stdin 的文件名。即

js
import foo from '-';

在任何文件中,都会提示 Rollup 尝试从 stdin 读取导入的文件并将默认导出分配给 foo。您可以将 --no-stdin CLI 标志传递给 Rollup,以将 - 视为常规文件名而不是。

由于某些插件依赖于文件扩展名来处理文件,因此您可以通过 --stdin=ext 为 stdin 指定文件扩展名,其中 ext 是所需的扩展名。在这种情况下,虚拟文件名将为 -.ext

shell
echo '{"foo": 42, "bar": "ok"}' | rollup --stdin=json -p json

JavaScript API 将始终将 --.ext 视为常规文件名。

根据 MIT 许可发布。