JavaScript API
Rollup は Node.js から利用可能な JavaScript API を提供します。これを使用する必要はめったになく、Rollup 自体を拡張する場合や、プログラムでバンドルを生成するなど、特殊な目的で使用する場合を除き、コマンドライン API を使用する方が適切です。
rollup.rollup
rollup.rollup
関数は、パラメータとして入力オプションオブジェクトを受け取り、以下に示すように、さまざまなプロパティとメソッドを持つ bundle
オブジェクトに解決される Promise を返します。このステップで、Rollup はモジュールグラフを構築し、ツリーシェイキングを実行しますが、出力は生成しません。
bundle
オブジェクトに対して、異なる出力オプションオブジェクトを使用して bundle.generate
を複数回呼び出すことで、異なるバンドルをインメモリで生成できます。ディスクに直接書き込みたい場合は、代わりに bundle.write
を使用してください。
bundle
オブジェクトの処理が完了したら、bundle.close()
を呼び出す必要があります。これにより、プラグインは closeBundle
フックを介して外部プロセスまたはサービスをクリーンアップできます。
どちらかの段階でエラーが発生した場合、エラーで拒否された Promise が返されます。エラーは code
プロパティで識別できます。code
と message
に加えて、多くのエラーには、カスタムレポートに使用できる追加のプロパティがあります。エラーとログの完全なリスト、およびそれらのコードとプロパティについては、utils/logs.ts
を参照してください。
import { rollup } from 'rollup';
// see below for details on these options
const inputOptions = {...};
// you can create multiple outputs from the same input to generate e.g.
// different formats like CommonJS and ESM
const outputOptionsList = [{...}, {...}];
build();
async function build() {
let bundle;
let buildFailed = false;
try {
// create a bundle
bundle = await rollup(inputOptions);
// an array of file names this bundle depends on
console.log(bundle.watchFiles);
await generateOutputs(bundle);
} catch (error) {
buildFailed = true;
// do some error reporting
console.error(error);
}
if (bundle) {
// closes the bundle
await bundle.close();
}
process.exit(buildFailed ? 1 : 0);
}
async function generateOutputs(bundle) {
for (const outputOptions of outputOptionsList) {
// generate output specific code in-memory
// you can call this function multiple times on the same bundle object
// replace bundle.generate with bundle.write to directly write to disk
const { output } = await bundle.generate(outputOptions);
for (const chunkOrAsset of output) {
if (chunkOrAsset.type === 'asset') {
// For assets, this contains
// {
// fileName: string, // the asset file name
// source: string | Uint8Array // the asset source
// type: 'asset' // signifies that this is an asset
// }
console.log('Asset', chunkOrAsset);
} else {
// For chunks, this contains
// {
// code: string, // the generated JS code
// dynamicImports: string[], // external modules imported dynamically by the chunk
// exports: string[], // exported variable names
// facadeModuleId: string | null, // the id of a module that this chunk corresponds to
// fileName: string, // the chunk file name
// implicitlyLoadedBefore: string[]; // entries that should only be loaded after this chunk
// imports: string[], // external modules imported statically by the chunk
// importedBindings: {[imported: string]: string[]} // imported bindings per dependency
// isDynamicEntry: boolean, // is this chunk a dynamic entry point
// isEntry: boolean, // is this chunk a static entry point
// isImplicitEntry: boolean, // should this chunk only be loaded after other chunks
// map: string | null, // sourcemaps if present
// modules: { // information about the modules in this chunk
// [id: string]: {
// renderedExports: string[]; // exported variable names that were included
// removedExports: string[]; // exported variable names that were removed
// renderedLength: number; // the length of the remaining code in this module
// originalLength: number; // the original length of the code in this module
// code: string | null; // remaining code in this module
// };
// },
// name: string // the name of this chunk as used in naming patterns
// preliminaryFileName: string // the preliminary file name of this chunk with hash placeholders
// referencedFiles: string[] // files referenced via import.meta.ROLLUP_FILE_URL_<id>
// type: 'chunk', // signifies that this is a chunk
// }
console.log('Chunk', chunkOrAsset.modules);
}
}
}
}
inputOptions オブジェクト
inputOptions
オブジェクトには、次のプロパティを含めることができます(詳細については、オプションの大きなリストを参照してください)。
const inputOptions = {
// 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,
perf
};
outputOptions オブジェクト
outputOptions
オブジェクトには、次のプロパティを含めることができます(詳細については、オプションの大きなリストを参照してください)。
const outputOptions = {
// 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,
reexportProtoFromExternal,
sanitizeFileName,
strict,
systemNullSetters,
// experimental
experimentalMinChunkSize
};
rollup.watch
Rollup は、個々のモジュールがディスク上で変更されたことを検出したときにバンドルを再構築する rollup.watch
関数も提供します。これは、コマンドラインから Rollup を --watch
フラグ付きで実行すると内部的に使用されます。JavaScript API を介してウォッチモードを使用する場合は、closeBundle
フックでプラグインがリソースをクリーンアップできるように、BUNDLE_END
イベントに応答して event.result.close()
を呼び出す必要があります。以下を参照してください。
const rollup = require('rollup');
const watchOptions = {...};
const watcher = rollup.watch(watchOptions);
watcher.on('event', event => {
// event.code can be one of:
// START — the watcher is (re)starting
// BUNDLE_START — building an individual bundle
// * event.input will be the input options object if present
// * event.output contains an array of the "file" or
// "dir" option values of the generated outputs
// BUNDLE_END — finished building a bundle
// * event.input will be the input options object if present
// * event.output contains an array of the "file" or
// "dir" option values of the generated outputs
// * event.duration is the build duration in milliseconds
// * event.result contains the bundle object that can be
// used to generate additional outputs by calling
// bundle.generate or bundle.write. This is especially
// important when the watch.skipWrite option is used.
// You should call "event.result.close()" once you are done
// generating outputs, or if you do not generate outputs.
// This will allow plugins to clean up resources via the
// "closeBundle" hook.
// END — finished building all bundles
// ERROR — encountered an error while bundling
// * event.error contains the error that was thrown
// * event.result is null for build errors and contains the
// bundle object for output generation errors. As with
// "BUNDLE_END", you should call "event.result.close()" if
// present once you are done.
// If you return a Promise from your event handler, Rollup will wait until the
// Promise is resolved before continuing.
});
// This will make sure that bundles are properly closed after each run
watcher.on('event', ({ result }) => {
if (result) {
result.close();
}
});
// Additionally, you can hook into the following. Again, return a Promise to
// make Rollup wait at that stage:
watcher.on('change', (id, { event }) => { /* a file was modified */ })
watcher.on('restart', () => { /* a new run was triggered */ })
watcher.on('close', () => { /* the watcher was closed, see below */ })
// to stop watching
watcher.close();
watchOptions
watchOptions
引数は、設定ファイルからエクスポートする設定(または設定の配列)です。
const watchOptions = {
...inputOptions,
output: [outputOptions],
watch: {
buildDelay,
chokidar,
clearScreen,
skipWrite,
exclude,
include
}
};
inputOptions
と outputOptions
の詳細については上記を参照するか、chokidar
、include
、および exclude
の情報については、オプションの大きなリストを参照してください。
設定ファイルをプログラムでロードする
このような設定の生成を支援するために、Rollup はコマンドラインインターフェースで設定ファイルをロードするために使用するヘルパーを別のエントリポイントを介して公開します。このヘルパーは、解決済みの fileName
と、オプションでコマンドラインパラメータを含むオブジェクトを受け取ります。
const { loadConfigFile } = require('rollup/loadConfigFile');
const path = require('node:path');
const rollup = require('rollup');
// load the config file next to the current script;
// the provided config object has the same effect as passing "--format es"
// on the command line and will override the format of all outputs
loadConfigFile(path.resolve(__dirname, 'rollup.config.js'), {
format: 'es'
}).then(async ({ options, warnings }) => {
// "warnings" wraps the default `onwarn` handler passed by the CLI.
// This prints all warnings up to this point:
console.log(`We currently have ${warnings.count} warnings`);
// This prints all deferred warnings
warnings.flush();
// options is an array of "inputOptions" objects with an additional
// "output" property that contains an array of "outputOptions".
// The following will generate all outputs for all inputs, and write
// them to disk the same way the CLI does it:
for (const optionsObj of options) {
const bundle = await rollup.rollup(optionsObj);
await Promise.all(optionsObj.output.map(bundle.write));
}
// You can also pass this directly to "rollup.watch"
rollup.watch(options);
});
高度なログフィルターの適用
コマンドラインインターフェースは、--filterLogs
フラグを介してログをフィルタリングする強力な方法を提供しますが、この機能は JavaScript API を使用する場合は直接利用できません。ただし、Rollup は、CLI と同じ構文を使用してフィルターを生成するためのヘルパー getLogFilter
を公開しています。これは、カスタムの onLog
ハンドラーを指定する場合や、Rollup CLI と同様のフィルタリングエクスペリエンスを提供したいサードパーティシステムに役立ちます。この関数は、文字列の配列を受け取ります。CLI のようにコンマ区切りのフィルターリストを分割しないことに注意してください。
// rollup.config.mjs
import { getLogFilter } from 'rollup/getLogFilter';
const logFilter = getLogFilter(['code:FOO', 'code:BAR']);
export default {
input: 'main.js',
output: { format: 'es' },
onLog(level, log, handler) {
if (logFilter(log)) {
handler(level, log);
}
}
};
パーサーへのアクセス
Rollup のパーサーを使用して任意のコードを解析するために、プラグインは this.parse
を使用できます。Rollup ビルドのコンテキスト外でこの機能を使用するために、パーサーは別のエクスポートとしても公開されています。これは this.parse
と同じシグネチャを持っています。
import { parseAst } from 'rollup/parseAst';
import assert from 'node:assert';
assert.deepEqual(
parseAst('return 42;', { allowReturnOutsideFunction: true }),
{
type: 'Program',
start: 0,
end: 10,
body: [
{
type: 'ReturnStatement',
start: 0,
end: 10,
argument: {
type: 'Literal',
start: 7,
end: 9,
raw: '42',
value: 42
}
}
],
sourceType: 'module'
}
);
Rollup の非 wasm ビルドでは、異なるスレッドで解析する非同期バージョンもあります。
import { parseAstAsync } from 'rollup/parseAst';
import assert from 'node:assert';
assert.deepEqual(
await parseAstAsync('return 42;', { allowReturnOutsideFunction: true }),
{
type: 'Program',
start: 0,
end: 10,
body: [
{
type: 'ReturnStatement',
start: 0,
end: 10,
argument: {
type: 'Literal',
start: 7,
end: 9,
raw: '42',
value: 42
}
}
],
sourceType: 'module'
}
);