Skip to content

命令行界面 ​

Rolldown 可以通过命令行使用。你可以提供可选的 Rolldown 配置文件,以简化命令行操作并启用 Rolldown 的高级功能。

配置文件 ​

Rolldown 配置文件虽然可选,但功能强大且使用方便,因此推荐使用。 配置文件是一个 ES 模块,默认导出包含所需选项的对象。 它通常命名为 rolldown.config.js,放在项目根目录中。 也可以在 CJS 文件中使用 CJS 语法,以 module.exports 代替 export default。 Rolldown 还原生支持 TypeScript 配置文件。

配置文件中可用选项的完整列表请参阅 官方 API 参考(英文)。

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

要让 Rolldown 使用配置文件,请传入 -c(或 --config)标志:

shell
rolldown -c                 # 使用 rolldown.config.{js,mjs,cjs,ts,mts,cts}
rolldown --config           # 与上面相同
rolldown -c my.config.js    # 使用自定义配置文件

如果没有传入文件名,Rolldown 会尝试加载工作目录中的 rolldown.config.{js,mjs,cjs,ts,mts,cts}。 如果找不到配置文件,Rolldown 会显示错误。

也可以从配置文件中导出函数。该函数会接收命令行参数,因此可以动态调整配置:

rolldown.config.js
js
import { defineConfig } from 'rolldown';

export default defineConfig((commandLineArgs) => {
  if (commandLineArgs.watch) {
    // 监听模式专用配置
  }
  return {
    input: 'src/main.js',
  };
});

配置加载器 ​

默认情况下,Rolldown 会先使用自身打包配置文件,再进行加载(configLoader: 'bundle')。这种方式适用于所有受支持的运行时,包括 TypeScript 配置。

如果运行时能够直接导入配置(Node.js 22.18+,原生支持移除 TypeScript 类型;Bun;Deno;或通过 --import 注册了 tsx、jiti 等加载器),可以使用 native 加载器跳过打包步骤:

shell
rolldown -c rolldown.config.ts --configLoader native

native 加载器更简单,并计划在未来成为默认方式。

配置智能提示 ​

Rolldown 自带 TypeScript 类型声明,因此可以通过 JSDoc 类型提示使用 IDE 的智能提示:

rolldown.config.js
js
/** @type {import('rolldown').RolldownOptions} */
export default {
  // ...
};

也可以使用 defineConfig 辅助函数,无需 JSDoc 注解即可获得智能提示:

rolldown.config.js
js
import { defineConfig } from 'rolldown';

export default defineConfig({
  // ...
});

配置数组 ​

要使用不同输入构建不同产物,可以提供配置对象数组:

rolldown.config.js
js
import { defineConfig } from 'rolldown';

export default defineConfig([
  {
    input: 'src/main.js',
    output: { format: 'esm', entryFileNames: 'bundle.esm.js' },
  },
  {
    input: 'src/main.js',
    output: { format: 'cjs', entryFileNames: 'bundle.cjs.js' },
  },
]);

使用相同输入生成不同输出

也可以为 output 选项提供数组,使用同一输入生成多个输出:

rolldown.config.js
js
import { defineConfig } from 'rolldown';

export default defineConfig({
  input: 'src/main.js',
  output: [
    { format: 'esm', entryFileNames: 'bundle.esm.js' },
    { format: 'cjs', entryFileNames: 'bundle.cjs.js' },
  ],
});

命令行标志 ​

标志可以采用 --foo、--foo <value> 或 --foo=<value> 的形式传入。--minify 等布尔标志不需要值,而 --transform.define 等键值选项使用逗号分隔语法:--transform.define key:value,key2:value2。许多标志都有短别名,例如 --minify 的别名是 -m,--format 的别名是 -f。

禁用布尔标志

要关闭布尔标志,请添加 --no- 前缀,例如 --no-minify 或 --no-codeSplitting。不支持把 false 作为值传入,例如 --minify false 或 --codeSplitting=false,这样做会报错,因为该值会被读取为字符串 "false",而不是布尔值。这与 Rollup CLI 的行为 一致(例如 --no-treeshake)。

一些标志既接受布尔值,也接受对象(例如 codeSplitting)。对于这类标志,可以:

  • 使用默认值启用:--codeSplitting
  • 禁用:--no-codeSplitting
  • 使用点号表示法设置嵌套字段:--codeSplitting.minSize 30000

集成到其他工具

请注意,在 Rolldown 收到参数前,shell 会先解释参数,因此引号和通配符的行为可能出乎意料。对于高级构建流程或与其他工具的集成,请考虑改用 JavaScript API。从配置文件切换到 API 时,主要区别如下:

许多选项都有对应的命令行标志。 这些标志的详情请参阅 官方 API 参考(英文)。 如果使用了配置文件,这里传入的参数会覆盖配置文件中的相应值。 下面列出所有受支持的标志:

sh
[log] Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API. (rolldown v1.2.0)

USAGE rolldown -c <config> or rolldown <input> <options>

OPTIONS

  --config -c, <filename>     Path to the config file (default: `rolldown.config.js`).
  --dir -d, <dir>             Output directory, defaults to `dist` if `file` is not set.
  --external -e, <external>   Comma-separated list of module ids to exclude from the bundle `<module-id>,...`.
  --format -f, <format>       Output format of the generated bundle (supports esm, cjs, and iife).
  --globals -g, <globals>     Global variable of UMD / IIFE dependencies (syntax: `key:value`).
  --help -h,                  Show help.
  --minify -m,                Minify the bundled file.
  --name -n, <name>           Name for UMD / IIFE format outputs.
  --file -o, <file>           Single output file.
  --platform -p, <platform>   Platform for which the code should be generated (node, browser, neutral).
  --sourcemap -s, <sourcemap> Generate sourcemap (`-s inline` for inline, or `-s` for `.map` file).
  --version -v,               Show version number.
  --watch -w,                 Watch files in bundle and rebuild on changes.
  --advancedChunks.minShareCount <advancedChunks.minShareCount>Minimum share count of the chunk.
  --advancedChunks.minSize <advancedChunks.minSize>Minimum size of the chunk.
  --assetFileNames <name>     Name pattern for asset files.
  --banner <banner>           Code to insert the top of the bundled file (outside the wrapper function).
  --checks.cannotCallNamespace Whether to emit warnings when a namespace is called as a function.
  --checks.circularDependency Whether to emit warnings when detecting circular dependency.
  --checks.commonJsVariableInEsm Whether to emit warnings when a CommonJS variable is used in an ES module.
  --checks.configurationFieldConflict Whether to emit warnings when a config value is overridden by another config value with a higher priority.
  --checks.couldNotCleanDirectory Whether to emit warnings when Rolldown could not clean the output directory.
  --checks.duplicateShebang   Whether to emit warnings when both the code and postBanner contain shebang.
  --checks.emptyImportMeta    Whether to emit warnings when `import.meta` is not supported with the output format and is replaced with an empty object (`{}`).
  --checks.eval               Whether to emit warnings when detecting uses of direct `eval`s.
  --checks.filenameConflict   Whether to emit warnings when files generated have the same name with different contents.
  --checks.importIsUndefined  Whether to emit warnings when an imported variable is not exported.
  --checks.ineffectiveDynamicImport Whether to emit warnings when a module is dynamically imported but also statically imported, making the dynamic import ineffective for code splitting.
  --checks.invalidAnnotation  Whether to emit warnings when a `#__PURE__` / `@__PURE__` annotation has no effect due to its position.
  --checks.largeBarrelModules Whether to emit info logs when a barrel module has a very large number of re-exports (more than 5000).
  --checks.missingGlobalName  Whether to emit warnings when the `output.globals` option is missing when needed.
  --checks.missingNameOptionForIifeExport Whether to emit warnings when the `output.name` option is missing when needed.
  --checks.mixedExports       Whether to emit warnings when the way to export values is ambiguous.
  --checks.pluginTimings      Whether to emit warnings when plugins take significant time during the build process.
  --checks.preferBuiltinFeature Whether to emit warnings when a plugin that is covered by a built-in feature is used.
  --checks.sourcemapBroken    Whether to emit warnings when a plugin transforms code without generating a sourcemap.
  --checks.toleratedTransform Whether to emit warnings when detecting tolerated transform.
  --checks.unresolvedEntry    Whether to emit warnings when an entrypoint cannot be resolved.
  --checks.unresolvedImport   Whether to emit warnings when an import cannot be resolved.
  --checks.unsupportedTsconfigOption Whether to emit warnings when a tsconfig option or combination of options is not supported.
  --chunkFileNames <name>     Name pattern for emitted secondary chunks.
  --cleanDir                  Clean output directory before emitting output.
  --codeSplitting <codeSplitting>Code splitting options. Enabled by default; use `--no-codeSplitting` to disable, or `--codeSplitting.minSize` / `--codeSplitting.minShareCount` to configure.
  --comments <comments>       Control comments in the output.
  --configLoader <loader>     How to load the config file (bundle, native).
  --context <context>         The entity top-level `this` represents.
  --cwd <cwd>                 Current working directory.
  --devtools.sessionId <devtools.sessionId>Used to name the build.
  --dynamicImportInCjs        Dynamic import in CJS output.
  --entryFileNames <name>     Name pattern for emitted entry chunks.
  --environment <environment> Pass additional settings to the config file via process.ENV.
  --esModule                  Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable).
  --exports <exports>         Specify a export mode (auto, named, default, none).
  --extend                    Extend global variable defined by name in IIFE / UMD formats.
  --footer <footer>           Code to insert the bottom of the bundled file (outside the wrapper function).
  --generatedCode.preset <generatedCode.preset>.
  --generatedCode.profilerNames Whether to add readable names to internal variables for profiling purposes.
  --generatedCode.symbols     Whether to use Symbol.toStringTag for namespace objects.
  --hashCharacters <hashCharacters>Use the specified character set for file hashes.
  --inlineDynamicImports      Inline dynamic imports.
  --input <input>             Entry file.
  --intro <intro>             Code to insert the top of the bundled file (inside the wrapper function).
  --keepNames                 Keep function and class names after bundling.
  --legalComments <legalComments>Control legal comments in the output.
  --logLevel <logLevel>       Log level (silent, info, debug, warn).
  --makeAbsoluteExternalsRelative Prevent normalization of external imports.
  --minifyInternalExports     Minify internal exports.
  --moduleTypes <types>       Module types for customized extensions.
  --no-externalLiveBindings   Disable external live bindings.
  --no-preserveEntrySignatures Avoid facade chunks for entry points.
  --no-treeshake              Disable treeshaking.
  --optimization.inlineConst <optimization.inlineConst>Enable crossmodule constant inlining.
  --optimization.pifeForModuleWrappers Use PIFE pattern for module wrappers.
  --outro <outro>             Code to insert the bottom of the bundled file (inside the wrapper function).
  --paths <paths>             Maps external module IDs to paths.
  --polyfillRequire           Disable require polyfill injection.
  --postBanner <postBanner>   A string to prepend to the top of each chunk. Applied after the `renderChunk` hook and minification.
  --postFooter <postFooter>   A string to append to the bottom of each chunk. Applied after the `renderChunk` hook and minification.
  --preserveModules           Preserve module structure.
  --preserveModulesRoot <preserveModulesRoot>Put preserved modules under this path at root level.
  --sanitizeFileName          Sanitize file name.
  --shimMissingExports        Create shim variables for missing exports.
  --sourcemapBaseUrl <sourcemapBaseUrl>Base URL used to prefix sourcemap paths.
  --sourcemapDebugIds         Inject sourcemap debug IDs.
  --sourcemapExcludeSources   Exclude source content from sourcemaps.
  --sourcemapFileNames <sourcemapFileNames>Name pattern for emitted sourcemaps.
  --strict <strict>           Whether to always output `"use strict"` directive in non-ES module outputs.
  --strictExecutionOrder      Lets modules be executed in the order they are declared.
  --topLevelVar               Rewrite top-level declarations to use `var`.
  --transform.assumptions.ignoreFunctionLength .
  --transform.assumptions.noDocumentAll .
  --transform.assumptions.objectRestNoSymbols .
  --transform.assumptions.pureGetters .
  --transform.assumptions.setPublicClassFields .
  --transform.decorator.emitDecoratorMetadata .
  --transform.decorator.legacy .
  --transform.decorator.strictNullChecks .
  --transform.define <transform.define>Define global variables (syntax: key:value,key2:value2).
  --transform.dropLabels <transform.dropLabels>Remove labeled statements with these label names.
  --transform.helpers.mode <transform.helpers.mode>.
  --transform.inject <transform.inject>Inject import statements on demand.
  --transform.jsx <transform.jsx>.
  --transform.plugins.styledComponents <transform.plugins.styledComponents>.
  --transform.plugins.taggedTemplateEscape .
  --transform.target <transform.target>The JavaScript target environment.
  --transform.typescript.allowDeclareFields .
  --transform.typescript.allowNamespaces .
  --transform.typescript.declaration.sourcemap .
  --transform.typescript.declaration.stripInternal .
  --transform.typescript.jsxPragma <transform.typescript.jsxPragma>.
  --transform.typescript.jsxPragmaFrag <transform.typescript.jsxPragmaFrag>.
  --transform.typescript.onlyRemoveTypeImports .
  --transform.typescript.optimizeConstEnums .
  --transform.typescript.optimizeEnums .
  --transform.typescript.removeClassFieldsWithoutInitializer .
  --transform.typescript.rewriteImportExtensions <transform.typescript.rewriteImportExtensions>.
  --tsconfig <tsconfig>       Path to the tsconfig.json file.
  --virtualDirname <virtualDirname>.

EXAMPLES

  1. Bundle with a config file `rolldown.config.mjs`:
    rolldown -c rolldown.config.mjs

  2. Bundle the `src/main.ts` to `dist` with `cjs` format:
    rolldown src/main.ts -d dist -f cjs

  3. Bundle the `src/main.ts` and handle the `.png` assets to Data URL:
    rolldown src/main.ts -d dist --moduleTypes .png=dataurl

  4. Bundle the `src/main.tsx` and minify the output with sourcemap:
    rolldown src/main.tsx -d dist -m -s

  5. Create self-executing IIFE using external jQuery as `$` and `_`:
    rolldown src/main.ts -d dist -n bundle -f iife -e jQuery,window._ -g jQuery=$

NOTES

  * CLI options will override the configuration file.
  * For more information, please visit https://rolldown.rs/.

以下标志只能通过命令行界面使用。

-c, --config <filename> ​

使用指定的配置文件。如果使用了该参数但未指定文件名,Rolldown 会查找默认配置文件。更多细节请参阅 配置文件。

--configLoader <loader> ​

配置文件的加载方式,可选值如下:

  • bundle(默认值):导入前先使用 Rolldown 打包配置。
  • native:直接导入配置,依靠运行时提供 TypeScript 和加载器支持。参阅 配置加载器。

-h / --help ​

显示帮助信息。

-v / --version ​

显示已安装的版本号。

-w / --watch ​

磁盘上的源文件发生变化时重新构建打包产物。

ROLLDOWN_WATCH 环境变量

在监听模式下,Rolldown 命令行界面会把 ROLLDOWN_WATCH 和 ROLLUP_WATCH 环境变量设置为 true,其他进程可以读取这些变量。插件应该改为检查 this.meta.watchMode,它不依赖命令行界面。

--environment <values> ​

通过 process.env 向配置文件传递额外设置。 值采用逗号分隔的键值对形式,其中值为 true 时可以省略。

例如:

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

这会设置 process.env.INCLUDE_DEPS = 'true' 和 process.env.BUILD = 'production'。

可以多次使用此选项。 后续设置的变量会覆盖之前的定义。

覆盖值

假设 package.json 中有以下脚本:

json
{
  "scripts": {
    "build": "rolldown -c --environment BUILD:production"
  }
}

可以通过 npm run build -- --environment BUILD:development 调用该脚本,将 process.env.BUILD 设置为 "development"。