Skip to content

命令行界面 ​

Rolldown 可以从命令行使用。你可以提供一个可选的 Rolldown 配置文件,以简化命令行用法并启用高级 Rolldown 功能。

配置文件 ​

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

请参阅 参考 以获取可包含在配置文件中的完整选项列表。

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) {
    // 仅用于 watch 的配置
  }
  return {
    input: 'src/main.js',
  };
});

配置加载器 ​

默认情况下,Rolldown 会先使用 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 类型定义,你可以利用 IDE 的 JSDoc 类型提示获得智能提示:

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

或者,你也可以使用 defineConfig 辅助函数,它无需 JSDoc 注解即可提供智能提示:

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

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

配置数组 ​

要从不同输入构建不同的 bundle,你可以提供一个配置对象数组:

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。许多标志都有简写别名(例如,-m 对应 --minify,-f 对应 --format)。

禁用布尔标志

要将布尔标志关闭,请在其前面加上 --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 时的关键区别:

许多选项都有对应的命令行标志。 有关这些标志的详细信息,请参阅 参考。 在这些情况下,如果你使用了配置文件,这里传入的任何参数都会覆盖配置文件中的设置。 下面是所有受支持标志的列表:

sh
Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API. (rolldown v1.2.11)

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.bundlerTimings     Whether to emit warnings when plugins and option callbacks take significant time during the build process.
  --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.moduleLevelDirective Whether to emit warnings for module-level directives other than `use strict`.
  --checks.namespaceConflict  Whether to emit warnings when multiple star re-exports provide the same name from different modules.
  --checks.pluginTimings      Deprecated alias for bundlerTimings. Rolldown uses bundlerTimings if both options have values.
  --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      Preserve source module execution order across generated chunks.
  --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 ​

当源文件在磁盘上发生变化时重新构建 bundle。

ROLLDOWN_WATCH 环境变量

在 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"。

Was this page helpful?