コマンドラインインターフェース
Rollupは通常、コマンドラインから使用する必要があります。コマンドラインの使用を簡素化し、高度なRollup機能を利用できるようにするために、オプションのRollup設定ファイルを提供できます。
設定ファイル
Rollup設定ファイルはオプションですが、強力で便利であるため、推奨されています。設定ファイルは、目的のオプションを持つデフォルトオブジェクトをエクスポートするESモジュールです。
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};
通常、rollup.config.js
またはrollup.config.mjs
と呼ばれ、プロジェクトのルートディレクトリにあります。--configPlugin
または--bundleConfigAsCjs
オプションを使用しない限り、RollupはNodeを直接使用してファイルをインポートします。RollupがNode ESMセマンティクスを遵守するため、ネイティブNode ESモジュールを使用する際の注意点があることに注意してください。
require
とmodule.exports
を使用して設定をCommonJSモジュールとして記述する場合は、ファイル拡張子を.cjs
に変更する必要があります。
TypeScriptのように設定ファイルに他の言語を使用することもできます。そのためには、@rollup/plugin-typescript
のような対応するRollupプラグインをインストールし、--configPlugin
オプションを使用します。
rollup --config rollup.config.ts --configPlugin typescript
--configPlugin
オプションを使用すると、設定ファイルは常に最初にCommonJSにトランスパイルされます。また、設定ファイルでTypeScript型を使用するより多くの方法については、設定インテリセンスも参照してください。
設定ファイルは、以下にリストされているオプションをサポートしています。各オプションの詳細については、オプションの大きなリストを参照してください。
// 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
}
};
設定ファイルから配列をエクスポートして、ウォッチモードでも、複数の無関係な入力から一度にバンドルをビルドできます。同じ入力で異なるバンドルをビルドするには、各入力に対して出力オプションの配列を指定します。
// 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
も処理できます。
// rollup.config.js
import fetch from 'node-fetch';
export default fetch('/some-remote-service-which-returns-actual-config');
同様に、次のようにすることもできます。
// rollup.config.js (Promise resolving an array)
export default Promise.all([fetch('get-config-1'), fetch('get-config-2')]);
設定ファイルでRollupを使用するには、--config
または-c
フラグを渡します。
# 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
を付けると、独自のコマンドラインオプションを定義することもできます。
// 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にコマンドライン引数を無視させることができます。
// 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型定義が含まれているため、JSDoc型ヒントを使用してIDEのインテリセンスを活用できます。
// rollup.config.js
/**
* @type {import('rollup').RollupOptions}
*/
const config = {
/* your config */
};
export default config;
または、JSDocアノテーションを必要とせずにインテリセンスを提供するdefineConfig
ヘルパーを使用できます。
// rollup.config.js
import { defineConfig } from 'rollup';
export default defineConfig({
/* your config */
});
RollupOptions
と、この型をカプセル化するdefineConfig
ヘルパーに加えて、次の型も役立つ可能性があります。
OutputOptions
:設定ファイルのoutput
部分Plugin
:name
といくつかのフックを提供するプラグインオブジェクト。すべてのフックは、プラグイン開発を支援するために完全に型付けされています。PluginImpl
:オプションオブジェクトをプラグインオブジェクトにマッピングする関数。ほとんどのパブリックRollupプラグインはこのパターンに従います。
--configPlugin
オプションを使用して、TypeScriptで直接設定を記述することもできます。TypeScriptを使用すると、RollupOptions
型を直接インポートできます。
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
にインストールされたパッケージから設定ファイルを読み込むこともサポートしています。
# 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を生成するために、次のアプローチをお勧めします。
// 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以降では、インポートアサーションを使用できます。
jsimport 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
を使用できます。jsimport { 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.dokyumento.jp/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にトランスパイルされます。
これにより、設定自体がESモジュールとして記述されている場合でも、構成で__dirname
やrequire.resolve
のようなCommonJSイディオムを使用できます。
--configPlugin <plugin>
設定ファイルのトランスパイルまたは解析の制御を行うRollupプラグインを指定できます。主な利点は、JavaScript以外の設定ファイルを使用できることです。たとえば、@rollup/plugin-typescript
がインストールされている場合、次を使用すると、TypeScriptで設定を記述できます。
rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript
TypeScriptの場合の注意点:tsconfig.json
のinclude
パスにRollup設定ファイルが含まれていることを確認してください。例えば
"include": ["src/**/*", "rollup.config.ts"],
このオプションは、--plugin
オプションと同じ構文をサポートしています。つまり、オプションを複数回指定したり、@rollup/plugin-
プレフィックスを省略してtypescript
と記述したり、={...}
を介してプラグインオプションを指定したりできます。
このオプションを使用すると、Rollupは最初に設定ファイルをESモジュールにトランスパイルしてから実行します。代わりにCommonJSにトランスパイルするには、--bundleConfigAsCjs
オプションも渡します。
--environment <values>
process.ENV
を介して追加の設定を設定ファイルに渡します。
rollup -c --environment INCLUDE_DEPS,BUILD:production
process.env.INCLUDE_DEPS === 'true'
とprocess.env.BUILD === 'production'
を設定します。このオプションは複数回使用できます。その場合、後続の設定変数は前の定義を上書きします。これにより、例えばpackage.json
スクリプトで環境変数を上書きできます。
{
"scripts": {
"build": "rollup -c --environment INCLUDE_DEPS,BUILD:production"
}
}
このスクリプトを介してこのスクリプトを呼び出すと
npm run build -- --environment BUILD:development
設定ファイルはprocess.env.INCLUDE_DEPS === 'true'
とprocess.env.BUILD === 'development'
を受け取ります。
--failAfterWarnings
ビルドが完了した後、警告が発生した場合、エラーでビルドを終了します。
--filterLogs <filter>
カスタムフィルターに基づいて、特定のログメッセージのみを表示します。最も基本的な形式では、フィルターはkey:value
ペアであり、keyはログオブジェクトのプロパティであり、valueは許可された値です。例えば
rollup -c --filterLogs code:EVAL
log.code === 'EVAL'
のログメッセージのみが表示されます。カンマで区切るか、オプションを複数回使用することで、複数のフィルターを指定できます。
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
を指定した場合と同じように処理され、カンマ区切りのフィルターリストをサポートします。
より複雑なフィルターに使用できる高度な構文もあります。
!
はフィルターを否定します。shellrollup -c --filterLogs "!code:CIRCULAR_DEPENDENCY"
循環依存関係の警告を除くすべてのログが表示されます。
*
は、フィルター値で使用する場合、任意のサブストリングと一致します。shellrollup -c --filterLogs "code:*_ERROR,message:*error*"
code
が_ERROR
で終わるか、メッセージに文字列error
が含まれているログのみが表示されます。&
は複数のフィルターを交差させます。shellrollup -c --filterLogs "code:CIRCULAR_DEPENDENCY&ids:*/main.js*"
code
が"CIRCULAR_DEPENDENCY"
であり、かつids
に/main.js
が含まれているログのみを表示します。これは別の機能を利用しています。値がオブジェクトの場合、フィルターを適用する前に
JSON.stringify
を介して文字列に変換されます。文字列以外の値は直接文字列にキャストされます。ネストされたプロパティもサポートされています。
shellrollup -c --filterLogs "foo.bar:value"
プロパティ
log.foo.bar
が値"value"
を持つログのみを表示します。
--forceExit
完了時にプロセスを強制終了します。プラグインまたはその依存関係が適切にクリーンアップされず、CLIプロセスが終了しない場合があります。根本原因の特定が困難な場合があるため、このフラグは原因を特定して解決するまでの間のエスケープハッチとして機能します。
これは特定のワークフローを中断させ、常に適切に動作するとは限らないことに注意してください。
-h
/--help
ヘルプドキュメントを表示します。
-p <plugin>
, --plugin <plugin>
指定されたプラグインを使用します。プラグインを指定する方法はいくつかあります。
相対パスによる指定
shellrollup -i input.js -f es -p ./my-plugin.js
ファイルはプラグインオブジェクトを返す関数をエクスポートする必要があります。
ローカルまたはグローバルの
node_modules
フォルダーにインストールされているプラグインの名前による指定shellrollup -i input.js -f es -p @rollup/plugin-node-resolve
プラグイン名が
rollup-plugin-
または@rollup/plugin-
で始まらない場合、Rollupはこれらのプレフィックスを自動的に追加しようとします。shellrollup -i input.js -f es -p node-resolve
インライン実装による指定
shellrollup -i input.js -f es -p '{transform: (c, i) => `/* ${JSON.stringify(i)} */\n${c}`}'
複数のプラグインをロードしたい場合は、オプションを繰り返すか、コンマ区切りの名前のリストを指定できます。
rollup -i input.js -f es -p node-resolve -p commonjs,json
デフォルトでは、プラグイン関数はプラグインを作成するための引数なしで呼び出されます。ただし、カスタム引数を渡すこともできます。
rollup -i input.js -f es -p 'terser={output: {beautify: true, indent_level: 2}}'
--silent
警告をコンソールに出力しません。構成ファイルに onLog
または onwarn
ハンドラーが含まれている場合、このハンドラーは引き続き呼び出されます。onLog
フックを持つプラグインも同様です。これを防ぐには、さらにlogLevel
オプションを使用するか、--logLevel silent
を渡してください。
--stdin=ext
stdinからコンテンツを読み取るときに、仮想ファイル拡張子を指定します。デフォルトでは、Rollupはstdinから読み取ったコンテンツに対して、拡張子のない仮想ファイル名 -
を使用します。ただし、一部のプラグインは、ファイルを処理するかどうかを判断するためにファイル拡張子に依存しています。 stdinからのファイルの読み取りも参照してください。
--no-stdin
stdin
からファイルを読み込まないでください。このフラグを設定すると、コンテンツをRollupにパイプすることができなくなり、Rollupが -
および -.[ext]
を stdin
の名前として解釈する代わりに、通常のファイル名として解釈するようになります。 stdinからのファイルの読み取りも参照してください。
-v
/--version
インストールされているバージョン番号を表示します。
--waitForBundleInput
これにより、エントリポイントファイルの1つが利用できない場合、エラーはスローされません。代わりに、すべてのファイルが揃うまでビルドを開始せずに待機します。これは、特に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>
ウォッチモードの場合、ウォッチイベントコードに対してシェルコマンド <cmd>
を実行します。 rollup.watch も参照してください。
rollup -c --watch --watch.onEnd="node ./afterBuildScript.js"
stdinからのファイルの読み取り
コマンドラインインターフェースを使用すると、Rollupはstdinからコンテンツを読み取ることもできます。
echo "export const foo = 42;" | rollup --format cjs --file out.js
このファイルにインポートが含まれている場合、Rollupは現在の作業ディレクトリを基準にしてそれらを解決しようとします。構成ファイルを使用する場合、Rollupはエントリポイントのファイル名が -
の場合にのみ、stdin
をエントリポイントとして使用します。stdinからエントリポイントではないファイルを読み取るには、内部的に stdin
を参照するために使用されるファイル名である -
という名前で呼び出すだけです。つまり、
import foo from '-';
ファイル内で、Rollupはstdinからインポートされたファイルを読み込もうとし、デフォルトのエクスポートを foo
に割り当てます。-
を通常のファイル名として扱うために、Rollupに --no-stdin
CLIフラグを渡すことができます。
一部のプラグインはファイルを処理するためにファイル拡張子に依存しているため、--stdin=ext
を介してstdinのファイル拡張子を指定できます。ここで、ext
は目的の拡張子です。その場合、仮想ファイル名は -.ext
になります。
echo '{"foo": 42, "bar": "ok"}' | rollup --stdin=json -p json
JavaScript APIは常に -
および -.ext
を通常のファイル名として扱います。