Skip to content

命令行接口

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

¥Rollup should typically be used from the command line. You can provide an optional Rollup configuration file to simplify command line usage and enable advanced Rollup functionality.

配置文件

¥Configuration Files

Rollup 配置文件是可选的,但它们功能强大且方便,因此推荐使用。配置文件是一个 ES 模块,它导出带有所需选项的默认对象:

¥Rollup configuration files are optional, but they are powerful and convenient and thus recommended. A config file is an ES module that exports a default object with the desired options:

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 会观察到 节点 ESM 语义

¥Typically, it is called rollup.config.js or rollup.config.mjs and sits in the root directory of your project. Unless the --configPlugin or --bundleConfigAsCjs options are used, Rollup will directly use Node to import the file. Note that there are some caveats when using native Node ES modules as Rollup will observe Node ESM semantics.

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

¥If you want to write your configuration as a CommonJS module using require and module.exports, you should change the file extension to .cjs.

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

¥You can also use other languages for your configuration files like TypeScript. To do that, install a corresponding Rollup plugin like @rollup/plugin-typescript and use the --configPlugin option:

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

使用 --configPlugin 选项将始终强制你的配置文件首先转换为 CommonJS。另请参阅 配置智能感知,了解在配置文件中使用 TypeScript 类型的更多方法。

¥Using the --configPlugin option will always force your config file to be transpiled to CommonJS first. Also have a look at Config Intellisense for more ways to use TypeScript typings in your config files.

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

¥Config files support the options listed below. Consult the big list of options for details on each option:

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
,
importAttributesKey
,
inlineDynamicImports
,
interop
,
intro
,
manualChunks
,
minifyInternalExports
,
outro
,
paths
,
preserveModules
,
preserveModulesRoot
,
sourcemap
,
sourcemapBaseUrl
,
sourcemapDebugIds
,
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
} };

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

¥You can export an array from your config file to build bundles from several unrelated inputs at once, even in watch mode. To build different bundles with the same input, you supply an array of output options for each input:

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

¥If you want to create your config asynchronously, Rollup can also handle a Promise which resolves to an object or an array.

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

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

同样,你也可以这样做:

¥Similarly, you can do this as well:

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

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

¥To use Rollup with a configuration file, pass the --config or -c flags:

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 作为前缀,你甚至可以定义自己的命令行选项:

¥You can also export a function that returns any of the above configuration formats. This function will be passed the current command line arguments so that you can dynamically adapt your configuration to respect e.g. --silent. You can even define your own command line options if you prefix them with 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,将使用调试配置。

¥If you now run rollup --config --configDebug, the debug configuration will be used.

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

¥By default, command line arguments will always override the respective values exported from a config file. If you want to change this behaviour, you can make Rollup ignore command line arguments by deleting them from the commandLineArgs object:

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
: {
/* ... */ } }; };

配置智能感知

¥Config Intellisense

由于 Rollup 附带 TypeScript 类型,因此你可以利用 IDE 的 Intellisense 和 JSDoc 类型提示:

¥Since Rollup ships with TypeScript typings, you can leverage your IDE's Intellisense with JSDoc type hints:

javascript
// rollup.config.js
/**

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

或者,你可以使用 defineConfig 辅助程序,它应该提供 Intellisense,而不需要 JSDoc 注释:

¥Alternatively you can use the defineConfig helper, which should provide Intellisense without the need for JSDoc annotations:

javascript
// rollup.config.js
import { 
defineConfig
} from 'rollup';
export default
defineConfig
({
/* your config */ });

除了封装此类型的 RollupOptionsdefineConfig 辅助程序之外,以下类型也很有用:

¥Besides RollupOptions and the defineConfig helper that encapsulates this type, the following types can prove useful as well:

  • OutputOptions:配置文件的 output 部分

    ¥OutputOptions: The output part of a config file

  • Plugin:提供 name 和一些钩子的插件对象。所有钩子都是完全类型化的,以帮助插件开发。

    ¥Plugin: A plugin object that provides a name and some hooks. All hooks are fully typed to aid in plugin development.

  • PluginImpl:将选项对象映射到插件对象的函数。大多数公共 Rollup 插件都遵循这种模式。

    ¥PluginImpl: A function that maps an options object to a plugin object. Most public Rollup plugins follow this pattern.

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

¥You can also directly write your config in TypeScript via the --configPlugin option. With TypeScript, you can import the RollupOptions type directly:

typescript
import type { RollupOptions } from 'rollup';

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

与 JavaScript API 的差异

¥Differences to the JavaScript API

虽然配置文件提供了一种简单的方法来配置 Rollup,但它们也限制了 Rollup 的调用和配置方式。特别是如果你将 Rollup 打包到另一个构建工具中或希望将其集成到高级构建过程中,那么最好直接从脚本中以编程方式调用 Rollup。

¥While config files provide an easy way to configure Rollup, they also limit how Rollup can be invoked and configured. Especially if you are bundling Rollup into another build tool or want to integrate it into an advanced build process, it may be better to directly invoke Rollup programmatically from your scripts.

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

¥If you want to switch from config files to using the JavaScript API at some point, there are some important differences to be aware of:

  • 使用 JavaScript API 时,传递给 rollup.rollup 的配置必须是对象,并且不能封装在 Promise 或函数中。

    ¥When using the JavaScript API, the configuration passed to rollup.rollup must be an object and cannot be wrapped in a Promise or a function.

  • 你不能再使用一系列配置。相反,你应该为每组 inputOptions 运行一次 rollup.rollup

    ¥You can no longer use an array of configurations. Instead, you should run rollup.rollup once for each set of inputOptions.

  • output 选项将被忽略。相反,你应该为每组 outputOptions 运行一次 bundle.generate(outputOptions)bundle.write(outputOptions)

    ¥The output option will be ignored. Instead, you should run bundle.generate(outputOptions) or bundle.write(outputOptions) once for each set of outputOptions.

从 Node 包加载配置

¥Loading a configuration from a Node package

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

¥For interoperability, Rollup also supports loading configuration files from packages installed into 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 模块时的注意事项

¥Caveats when using native Node ES modules

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

¥Especially when upgrading from an older Rollup version, there are some things you need to be aware of when using a native ES module for your configuration file.

获取当前目录

¥Getting the current directory

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

¥With CommonJS files, people often use __dirname to access the current directory and resolve relative paths to absolute paths. This is not supported for native ES modules. Instead, we recommend the following approach e.g. to generate an absolute id for an external module:

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

¥Importing package.json

将包文件导入到例如 自动将你的依赖标记为 "external"。根据你的 Node 版本,有不同的方法可以做到这一点:

¥It can be useful to import your package file to e.g. mark your dependencies as "external" automatically. Depending on your Node version, there are different ways of doing that:

  • 对于 Node 18.20+,你可以使用导入属性

    ¥For Node 18.20+, you can use an import attribute

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

    ¥For older Node versions, you can use createRequire

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

    ¥Or just directly read and parse the file from disk

    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://nodejs.cn/docs/latest-v16.x/api/esm.html#importmetaurl const
    packageJson
    =
    JSON
    .
    parse
    (
    readFileSync
    (new
    URL
    ('./package.json', import.meta.
    url
    ))
    ); // ...

命令行标志

¥Command line flags

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

¥Many options have command line equivalents. In those cases, any arguments passed here will override the config file, if you're using one. This is a list of all supported options:

-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
--importAttributesKey <name> Use the specified keyword for import attributes
--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
--sourcemapDebugIds         Emit unique debug ids in source and sourcemaps
--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

下面列出的标志只能通过命令行接口使用。所有其他标志对应并覆盖其配置文件等效项,请参阅 选项清单 了解详细信息。

¥The flags listed below are only available via the command line interface. All other flags correspond to and override their config file equivalents, see the big list of options for details.

--bundleConfigAsCjs

此选项将强制将你的配置转换为 CommonJS。

¥This option will force your configuration to be transpiled to CommonJS.

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

¥This allows you to use CommonJS idioms like __dirname or require.resolve in your configuration even if the configuration itself is written as an ES module.

--configImportAttributesKey <with | assert>

控制 Rollup 在配置文件中用于导入属性的关键字。

¥Controls the keyword Rollup uses for import attributes in your config file.

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

此选项仅在使用 --configPlugin--bundleConfigAsCjs 选项时可用。

¥This option only available if the --configPlugin or --bundleConfigAsCjs options are used.

--configPlugin <plugin>

允许指定 Rollup 插件来转译或以其他方式控制配置文件的解析。主要好处是它允许你使用非 JavaScript 配置文件。例如,如果你安装了 @rollup/plugin-typescript,以下命令将允许你在 TypeScript 中编写配置:

¥Allows specifying Rollup plugins to transpile or otherwise control the parsing of your configuration file. The main benefit is that it allows you to use non-JavaScript configuration files. For instance the following will allow you to write your configuration in TypeScript, provided you have @rollup/plugin-typescript installed:

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

TypeScript 注意事项:确保你的 tsconfig.jsoninclude 路径中有 Rollup 配置文件。例如:

¥Note for Typescript: make sure you have the Rollup config file in your tsconfig.json's include paths. For example:

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

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

¥This option supports the same syntax as the --plugin option i.e., you can specify the option multiple times, you can omit the @rollup/plugin- prefix and just write typescript and you can specify plugin options via ={...}.

使用此选项将使 Rollup 在执行之前首先将你的配置文件转换为 ES 模块。要转译为 CommonJS,还要传递 --bundleConfigAsCjs 选项。

¥Using this option will make Rollup transpile your configuration file to an ES module first before executing it. To transpile to CommonJS instead, also pass the --bundleConfigAsCjs option.

--environment <values>

通过 process.ENV 将附加设置传递到配置文件。

¥Pass additional settings to the config file via process.ENV.

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

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

¥will set process.env.INCLUDE_DEPS === 'true' and process.env.BUILD === 'production'. You can use this option several times. In that case, subsequently set variables will overwrite previous definitions. This enables you for instance to overwrite environment variables in package.json scripts:

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

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

¥If you call this script via:

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

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

¥then the config file will receive process.env.INCLUDE_DEPS === 'true' and process.env.BUILD === 'development'.

--failAfterWarnings

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

¥Exit the build with an error if any warnings occurred, once the build is complete.

--filterLogs <filter>

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

¥Only display certain log messages based on custom filters. In its most basic form, a filter is a key:value pair where the key is a property of the log object and the value is an allowed value. For instance

shell
rollup -c --filterLogs code:EVAL

将仅显示 log.code === 'EVAL'。你可以通过用逗号分隔或多次使用该选项来指定多个过滤器:

¥will only display log messages where log.code === 'EVAL'. You can specify multiple filters by separating them with a comma or using the option multiple times:

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

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

¥This will display all logs where the code is either "FOO" or "BAR" or where the message is "This is the message".

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

¥For situations where you cannot easily add additional command line parameters, you can also use the ROLLUP_FILTER_LOGS environment variable. The value of this variable will be handled the same way as if you specified --filterLogs on the command line and supports a comma-separated list of filters.

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

¥There is also some advanced syntax available for more complex filters.

  • ! 将取消过滤器:

    ¥! will negate a filter:

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

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

    ¥will display all logs except circular dependency warnings.

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

    ¥* matches any sub-string when used in a filter value:

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

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

    ¥will only display logs where either the code ends with _ERROR or the message contains the string error.

  • & 与多个过滤器相交:

    ¥& intersects several filters:

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

    只会显示 code"CIRCULAR_DEPENDENCY" 并且 ids 包含 /main.js 的日志。这利用了另一个功能:

    ¥will only display logs where both the code is "CIRCULAR_DEPENDENCY" and the ids contain /main.js. This makes use of another feature:

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

    ¥if the value is an object, it will be converted to a string via JSON.stringify before applying the filter. Other non-string values will be directly cast to string.

  • 还支持嵌套属性:

    ¥nested properties are supported as well:

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

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

    ¥will only display logs where the property log.foo.bar has the value "value".

--forceExit

完成后强制退出进程。在某些情况下,插件或其依赖可能无法正确清理并阻止 CLI 进程退出。根本原因可能很难诊断,而此标志提供了一个应急方案,直到可以识别和解决它。

¥Force exit the process when done. In some cases plugins or their dependencies might not cleanup properly and prevent the CLI process from exiting. The root cause can be hard to diagnose and this flag provides an escape hatch until it can be identified and resolved.

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

¥Note that this might break certain workflows and won't always work properly.

-h/--help

打印帮助文档。

¥Print the help document.

-p <plugin>--plugin <plugin>

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

¥Use the specified plugin. There are several ways to specify plugins here:

  • 通过相对路径:

    ¥Via a relative path:

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

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

    ¥The file should export a function returning a plugin object.

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

    ¥Via the name of a plugin that is installed in a local or global node_modules folder:

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

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

    ¥If the plugin name does not start with rollup-plugin- or @rollup/plugin-, Rollup will automatically try adding these prefixes:

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

    ¥Via an inline implementation:

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

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

¥If you want to load more than one plugin, you can repeat the option or supply a comma-separated list of names:

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

默认情况下,将不带参数调用插件函数来创建插件。但是,你也可以传递自定义参数:

¥By default, plugin functions will be called with no argument to create the plugin. You can however pass a custom argument as well:

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

--silent

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

¥Don't print warnings to the console. If your configuration file contains an onLog or onwarn handler, this handler will still be called. The same goes for plugins with an onLog hook. To prevent that, additionally use the logLevel option or pass --logLevel silent.

--stdin=ext

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

¥Specify a virtual file extension when reading content from stdin. By default, Rollup will use the virtual file name - without an extension for content read from stdin. Some plugins, however, rely on file extensions to determine if they should process a file. See also Reading a file from stdin.

--no-stdin

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

¥Do not read files from stdin. Setting this flag will prevent piping content to Rollup and make sure Rollup interprets - and -.[ext] as a regular file names instead of interpreting these as the name of stdin. See also Reading a file from stdin.

-v/--version

打印安装的版本号。

¥Print the installed version number.

--waitForBundleInput

如果入口点文件之一不可用,这不会引发错误。相反,它将等到所有文件都存在后再开始构建。这很有用,特别是在监视模式下,当 Rollup 正在消耗另一个进程的输出时。

¥This will not throw an error if one of the entry point files is not available. Instead, it will wait until all files are present before starting the build. This is useful, especially in watch mode, when Rollup is consuming the output of another process.

-w/--watch

当磁盘上的源文件发生更改时,重新构建打包包。

¥Rebuild the bundle when its source files change on disk.

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

¥Note: While in watch mode, the ROLLUP_WATCH environment variable will be set to "true" by Rollup's command line interface and can be checked by other processes. Plugins should instead check this.meta.watchMode, which is independent of the command line interface.

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

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

¥When in watch mode, run a shell command <cmd> for a watch event code. See also rollup.watch.

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

从 stdin 读取文件

¥Reading a file from stdin

使用命令行接口时,Rollup 还可以从 stdin 读取内容:

¥When using the command line interface, Rollup can also read content from stdin:

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

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

¥When this file contains imports, Rollup will try to resolve them relative to the current working directory. When using a config file, Rollup will only use stdin as an entry point if the file name of the entry point is -. To read a non-entry-point file from stdin, just call it -, which is the file name that is used internally to reference stdin. I.e.

js
import foo from '-';

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

¥in any file will prompt Rollup to try to read the imported file from stdin and assign the default export to foo. You can pass the --no-stdin CLI flag to Rollup to treat - as a regular file name instead.

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

¥As some plugins rely on file extensions to process files, you can specify a file extension for stdin via --stdin=ext where ext is the desired extension. In that case, the virtual file name will be -.ext:

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

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

¥The JavaScript API will always treat - and -.ext as regular file names.