跳至內容

命令列介面

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。另請參閱 組態 Intellisense,以取得在組態檔中使用 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: { ... }
  }
}

設定檔 Intellisense

由於 Rollup 附帶 TypeScript 型別,您可以利用 IDE 的 Intellisense 搭配 JSDoc 型別提示

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

或者,您可以使用 defineConfig 輔助函式,它應該可以在不需要 JSDoc 註解的情況下提供 Intellisense

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

匯入 package 檔案可能很有用,例如自動將相依性標記為「外部」。根據 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.dev.org.tw/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 組態檔。例如,如果您已安裝 @rollup/plugin-typescript,以下範例將允許您使用 TypeScript 編寫組態

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

TypeScript 注意事項:請確定您的 Rollup 組態檔在 tsconfig.jsoninclude 路徑中。例如

"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 成對,其中 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 結尾或訊息包含字串 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 授權下發布。