組態選項
核心功能
external
類型 | (字串 | RegExp)[]| RegExp| 字串| (id: 字串, parentId: 字串, isResolved: 布林) => 布林 |
---|---|
CLI | -e /--external <external-id,another-external-id,...> |
一個函式,接收一個 id
並回傳 true
(外部)或 false
(非外部),或一個模組 ID 的陣列,或用於比對模組 ID 的正規表示式,這些模組 ID 應保持在套件外部。也可以只是一個單一的 ID 或正規表示式。比對到的 ID 應為
- 外部依賴的名稱,與匯入陳述式中寫入的方式完全相同。亦即,若要將
import "dependency.js"
標記為外部,請使用"dependency.js"
,而若要將import "dependency"
標記為外部,請使用"dependency"
。 - 已解析的 ID(例如檔案的絕對路徑)。
// rollup.config.js
import { fileURLToPath } from 'node:url';
export default {
//...,
external: [
'some-externally-required-library',
fileURLToPath(
new URL(
'src/some-local-file-that-should-not-be-bundled.js',
import.meta.url
)
),
/node_modules/
]
};
請注意,如果你想透過 /node_modules/
正規表示法篩選套件匯入,例如 import {rollup} from 'rollup'
,你需要類似 @rollup/plugin-node-resolve 的東西,才能先將匯入解析到 node_modules
。
當作為命令列參數提供時,它應該是 ID 的逗號分隔清單
rollup -i src/main.js ... -e foo,bar,baz
提供函式時,會呼叫它,並提供三個參數 (id, parent, isResolved)
,這些參數可以讓你更精細地控制
id
是相關模組的 idparent
是執行匯入的模組的 idisResolved
表示id
是否已由例如外掛程式解析
建立 iife
或 umd
捆綁時,你需要透過 output.globals
選項提供全域變數名稱,以取代你的外部匯入。
如果相對匯入,亦即以 ./
或 ../
開頭,被標記為「外部」,rollup 會在內部將 id 解析為絕對檔案系統位置,以便可以合併外部模組的不同匯入。寫入產生的捆綁時,匯入會再次轉換為相對匯入。範例
// input
// src/main.js (entry point)
import x from '../external.js';
import './nested/nested.js';
console.log(x);
// src/nested/nested.js
// the import would point to the same file if it existed
import x from '../../external.js';
console.log(x);
// output
// the different imports are merged
import x from '../external.js';
console.log(x);
console.log(x);
轉換回相對匯入的方式,就像 output.file
或 output.dir
出現在與進入點相同的位置,或者如果有超過一個進入點,則出現在所有進入點的共同基本目錄中。
輸入
類型 | 字串 | 字串陣列 | { [entryName: 字串]: 字串 } |
---|---|
CLI | -i /--input <filename> |
套件的進入點(例如您的 main.js
或 app.js
或 index.js
)。如果您提供進入點陣列或將名稱對應到進入點的物件,它們將會被套件化成個別的輸出區塊。除非使用 output.file
選項,否則產生的區塊名稱將遵循 output.entryFileNames
選項。使用物件形式時,檔案名稱的 [name]
部分將會是物件屬性的名稱,而使用陣列形式時,它將會是進入點的檔案名稱。
請注意,在使用物件形式時,可以透過在名稱中加入 /
來將進入點放入不同的子資料夾。下列範例將產生至少兩個進入區塊,名稱分別為 entry-a.js
和 entry-b/index.js
,也就是說檔案 index.js
會被放置在 entry-b
資料夾中
// rollup.config.js
export default {
...,
input: {
a: 'src/main-a.js',
'b/index': 'src/main-b.js'
},
output: {
...,
entryFileNames: 'entry-[name].js'
}
};
如果您想要將一組檔案轉換成另一種格式,同時保留檔案結構和匯出簽章,建議的方式(而非使用 output.preserveModules
,它可能會樹狀搖晃匯出以及發出由外掛程式建立的虛擬檔案)是將每個檔案都變成一個進入點。您可以動態執行此操作,例如透過 glob
套件
import { globSync } from 'glob';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
export default {
input: Object.fromEntries(
globSync('src/**/*.js').map(file => [
// This remove `src/` as well as the file extension from each
// file, so e.g. src/nested/foo.js becomes nested/foo
path.relative(
'src',
file.slice(0, file.length - path.extname(file).length)
),
// This expands the relative paths to absolute paths, so e.g.
// src/nested/foo becomes /project/src/nested/foo.js
fileURLToPath(new URL(file, import.meta.url))
])
),
output: {
format: 'es',
dir: 'dist'
}
};
如果某個外掛程式在 buildStart
鉤子的最後使用 this.emitFile
發出至少一個區塊,則可以省略此選項。
使用命令列介面時,可以透過多次使用此選項來提供多個輸入。當作為第一個選項提供時,等同於不使用 --input
為其加上前綴
rollup --format es --input src/entry1.js --input src/entry2.js
# is equivalent to
rollup src/entry1.js src/entry2.js --format es
區塊可透過在提供的數值中加入 =
來命名
rollup main=src/entry1.js other=src/entry2.js --format es
包含空白字元的檔案名稱可透過使用引號來指定
rollup "main entry"="src/entry 1.js" "src/other entry.js" --format es
output.dir
類型 | 字串 |
---|---|
CLI | -d /--dir <dirname> |
放置所有已產生區塊的目錄。如果產生多個區塊,此選項為必要。否則,可以使用 file
選項。
output.file
類型 | 字串 |
---|---|
CLI | -o /--file <filename> |
要寫入的檔案。也會用於產生原始碼對應,如果適用。僅當產生不超過一個區塊時才能使用。
output.format
類型 | 字串 |
---|---|
CLI | -f /--format <formatspecifier> |
預設 | "es" |
指定已產生套件的格式。下列其中之一
amd
– 非同步模組定義,用於像 RequireJS 這類的模組載入器cjs
– CommonJS,適合 Node 和其他套件管理工具(別名:commonjs
)es
– 將套件保持為 ES 模組檔案,適合其他套件管理工具和包含在現代瀏覽器的<script type=module>
標籤中(別名:esm
、module
)iife
– 自我執行函式,適合包含在<script>
標籤中。(如果你想為你的應用程式建立套件,你可能會想使用這個)。「iife」代表「立即呼叫的 函式表達式」umd
– 通用模組定義,同時作為amd
、cjs
和iife
system
– SystemJS 載入器的原生格式(別名:systemjs
)
output.globals
類型 | { [id: 字串]: 字串 }| ((id: 字串) => 字串) |
---|---|
CLI | -g /--globals <外部 id: 變數名稱, 另一個外部 id: 另一個變數名稱,...> |
指定 id: 變數名稱
對,這對 umd
/iife
捆綁中的外部匯入是必要的。例如,在這種情況下…
import $ from 'jquery';
…我們想要告訴 Rollup,jquery
是外部的,而 jquery
模組 ID 等於全域 $
變數
// rollup.config.js
export default {
...,
external: ['jquery'],
output: {
format: 'iife',
name: 'MyBundle',
globals: {
jquery: '$'
}
}
};
/*
var MyBundle = (function ($) {
// code goes here
}($));
*/
或者,提供一個函式,將外部模組 ID 轉換為全域變數名稱。
當作為命令列引數給出時,它應該是 id: 變數名稱
對的逗號分隔清單
rollup -i src/main.js ... -g jquery:$,underscore:_
若要告訴 Rollup 本地檔案應該由全域變數取代,請使用絕對 id
// rollup.config.js
import { fileURLToPath } from 'node:url';
const externalId = fileURLToPath(
new URL(
'src/some-local-file-that-should-not-be-bundled.js',
import.meta.url
)
);
export default {
//...,
external: [externalId],
output: {
format: 'iife',
name: 'MyBundle',
globals: {
[externalId]: 'globalVariable'
}
}
};
output.name
類型 | 字串 |
---|---|
CLI | -n /--name <變數名稱> |
對於 iife
/umd
捆綁是必要的,它會匯出值,在這種情況下,它是代表您的捆綁的全域變數名稱。同一頁面上的其他指令碼可以使用此變數名稱存取您的捆綁的匯出。
// rollup.config.js
export default {
...,
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyBundle'
}
};
// var MyBundle = (function () {...
支援命名空間,即您的名稱可以包含點。產生的捆綁將包含命名空間所需的設定。
rollup -n "a.b.c"
/* ->
this.a = this.a || {};
this.a.b = this.a.b || {};
this.a.b.c = ...
*/
output.plugins
類型 | MaybeArray<MaybePromise<OutputPlugin | void>> |
---|
僅針對此輸出新增外掛程式。請參閱 使用輸出外掛程式,以取得有關如何使用輸出特定外掛程式的更多資訊,以及 外掛程式,以取得有關如何撰寫您自己的外掛程式的資訊。對於從套件匯入的外掛程式,請記得呼叫匯入的外掛程式函式(即 commonjs()
,而不仅仅是 commonjs
)。假值外掛程式將被忽略,這可以用於輕鬆啟用或停用外掛程式。巢狀外掛程式將會扁平化。非同步外掛程式將會等待並解析。
並非所有外掛都能在此使用。output.plugins
僅限於僅使用在 bundle.generate()
或 bundle.write()
中執行的掛鉤的外掛,亦即在 Rollup 的主要分析完成之後。如果您是外掛作者,請參閱 輸出產生掛鉤 以找出可以使用哪些掛鉤。
以下將新增壓縮功能至其中一個輸出
// rollup.config.js
import terser from '@rollup/plugin-terser';
export default {
input: 'main.js',
output: [
{
file: 'bundle.js',
format: 'es'
},
{
file: 'bundle.min.js',
format: 'es',
plugins: [terser()]
}
]
};
外掛
類型 | MaybeArray<MaybePromise<Plugin | void>> |
---|
請參閱 使用外掛 以取得更多有關如何使用外掛的資訊,以及 外掛 以取得有關如何撰寫您自己的外掛的資訊(試試看,這並不難,而且可以大幅擴充您可以使用 Rollup 執行的功能)。對於從套件匯入的外掛,請記得呼叫匯入的外掛函式(亦即 commonjs()
,而不僅僅是 commonjs
)。假值外掛將會被忽略,這可以用於輕鬆啟用或停用外掛。巢狀外掛將會扁平化。非同步外掛將會被等待並解析。
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
const isProduction = process.env.NODE_ENV === 'production';
export default (async () => ({
input: 'main.js',
plugins: [
resolve(),
commonjs(),
isProduction && (await import('@rollup/plugin-terser')).default()
],
output: {
file: 'bundle.js',
format: 'cjs'
}
}))();
(此範例也示範如何使用非同步 IIFE 和動態匯入來避免不必要的模組載入,這可能會意外地緩慢。)
進階功能
快取
類型 | RollupCache | 布林值 |
---|---|
預設 | true |
先前組合的 cache
屬性。在監控模式中使用它來加速後續建置 — Rollup 將僅重新分析已變更的模組。將此選項明確設定為 false
將會防止在組合中產生 cache
屬性,並停用外掛快取。
const rollup = require('rollup');
let cache;
async function buildWithCache() {
const bundle = await rollup.rollup({
cache // is ignored if falsy
// ... other input options
});
cache = bundle.cache; // store the cache object of the previous build
return bundle;
}
buildWithCache()
.then(bundle => {
// ... do something with the bundle
})
.then(() => buildWithCache()) // will use the cache of the previous build
.then(bundle => {
// ... do something with the bundle
});
logLevel
類型 | LogLevel | "silent" |
---|---|
CLI | --logLevel <level> |
預設 | "info" |
決定要處理哪些記錄。請參閱 onLog
以取得可用的記錄層級。預設的 logLevel
為 "info"
,表示將處理資訊和警告記錄,而偵錯記錄將被忽略,這表示它們既不會傳遞給外掛 onLog
鉤子或 onLog
選項,也不會列印到主控台。
使用 CLI 時,錯誤仍會列印到主控台,因為它們不會透過記錄系統處理。請參閱 --silent
旗標,了解如何抑制錯誤記錄。
makeAbsoluteExternalsRelative
類型 | 布林值 | "ifRelativeSource" |
---|---|
CLI | --makeAbsoluteExternalsRelative /--no-makeAbsoluteExternalsRelative |
預設 | "ifRelativeSource" |
決定是否應將輸出中的絕對外部路徑轉換為相對路徑。這不僅適用於來源中為絕對路徑的路徑,也適用於由外掛或 Rollup 核心解析為絕對路徑的路徑。
對於 true
,外部匯入(例如 import "/Users/Rollup/project/relative.js"
)將轉換為相對路徑。在將絕對路徑轉換為相對路徑時,Rollup 不會考量 file
或 dir
選項,因為這些選項可能不存在,例如對於使用 JavaScript API 的建置。相反地,它假設已產生套件的根目錄位於包含在套件中所有模組的共用共用父目錄。假設所有模組的共用父目錄為 "/Users/Rollup/project"
,則來自上方的匯入可能會在輸出中轉換為 import "./relative.js"
。如果輸出區塊本身嵌套在子目錄中,例如選擇 chunkFileNames: "chunks/[name].js"
,則匯入將會是 "../relative.js"
。
如前所述,這也適用於最初的相對匯入,例如 import "./relative.js"
,在它們被 external
選項標記為外部之前,會解析為絕對路徑。
一個常見的問題是,此機制也適用於匯入,例如 import "/absolute.js'"
,導致輸出中出現意外的相對路徑。
對於此情況,"ifRelativeSource"
會檢查原始匯入是否為相對匯入,然後才將其轉換為輸出中的相對匯入。選擇 false
將保留輸出中所有路徑為絕對路徑。
請注意,當使用 external
選項將相對路徑直接標記為「外部」時,它將會是輸出中的相同相對路徑。當它首先透過外掛程式或 Rollup 核心解析,然後標記為外部時,將套用上述邏輯。
maxParallelFileOps
類型 | 數字 |
---|---|
CLI | --maxParallelFileOps <數字> |
預設 | 20 |
限制 Rollup 在讀取模組或寫入區塊時並行開啟的檔案數量。沒有限制或值夠高時,建置可能會失敗,並出現「EMFILE:開啟的檔案太多」的訊息。這取決於作業系統允許開啟多少個檔案處理序。
onLog
類型 | (層級:LogLevel,記錄:RollupLog,預設處理常式:LogOrStringHandler) => void; |
---|
type LogLevel = 'warn' | 'info' | 'debug';
type LogOrStringHandler = (
level: LogLevel | 'error',
log: string | RollupLog
) => void;
// All possible properties, actual properties depend on log
interface RollupLog {
binding?: string;
cause?: Error;
code?: string;
exporter?: string;
frame?: string; // always printed by the CLI
hook?: string;
id?: string; // always printed by the CLI
ids?: string[];
loc?: {
column: number;
file?: string;
line: number;
}; // always printed by the CLI if id is present
message: string; // the actual message, always printed by the CLI
meta?: any; // add custom plugin properties to logs
names?: string[];
plugin?: string; // added by Rollup for plugin logs, only printed for warnings
pluginCode?: string; // added by Rollup for plugin logs that contain a code
pos?: number;
reexporter?: string;
stack?: string; // url for additional information, always printed by the CLI
url?: string;
}
攔截記錄訊息的函數。若未提供,記錄會列印至主控台,而 Rollup CLI 會彙總某些 "warn"
記錄,並在建置後列印整合的警告,以減少雜訊。使用 --silent
CLI 選項時,也會觸發此處理常式。
此函數會收到三個參數:記錄層級、記錄物件和預設處理常式。記錄物件至少具有 code
和 message
屬性,讓您控制如何處理不同類型的記錄。其他屬性會根據記錄類型而新增。請參閱 utils/logs.ts
,以取得內建錯誤和記錄的完整清單,以及其代碼和屬性。
若未呼叫預設處理常式,記錄不會列印至主控台。此外,您可以透過以不同層級呼叫預設處理常式,來變更記錄層級。使用額外的層級 "error"
,會將記錄轉換為拋出的錯誤,該錯誤具有記錄的所有附加屬性。
// rollup.config.js
export default {
//...
onLog(level, log, handler) {
if (log.code === 'CIRCULAR_DEPENDENCY') {
return; // Ignore circular dependency warnings
}
if (level === 'warn') {
handler('error', log); // turn other warnings into errors
} else {
handler(level, log); // otherwise, just print the log
}
}
};
若記錄已由 logLevel
選項篩選出來,則不會呼叫此處理常式。亦即,預設情況下,"debug"
記錄會被吞掉。
某些記錄還具有 loc
屬性和 frame
,讓您可以找出記錄的來源
// rollup.config.js
export default {
//...
onLog(level, { loc, frame, message }) {
if (loc) {
console.warn(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
if (frame) console.warn(frame);
} else {
console.warn(message);
}
}
};
onwarn
類型 | (警告:RollupLog,預設處理常式: (警告:字串 | RollupLog) => void) => void; |
---|
會攔截警告訊息的函數。它與 onLog
非常相似,但只會接收警告。若呼叫預設處理常式,記錄會被視為警告處理。若同時提供了 onLog
和 onwarn
處理常式,則只有當 onLog
以 warn
的 level
呼叫其預設處理常式時,才會呼叫 onwarn
處理常式。
有關更多資訊,請參閱 onLog
。
output.assetFileNames
類型 | 字串 | ((assetInfo: AssetInfo) => 字串) |
---|---|
CLI | --assetFileNames <模式> |
預設 | "assets/[name]-[hash][extname]" |
用於命名自訂發射的資產,以包含在建置輸出中,或一個函式,每個資產呼叫一次以傳回此類模式。模式支援下列佔位符
[extname]
:資產的檔案副檔名,包含前導點,例如.css
。[ext]
:檔案副檔名,不含前導點,例如css
。[hash]
:根據資產內容的雜湊。您也可以透過例如[hash:10]
設定特定的雜湊長度。預設情況下,它會建立一個 base-64 雜湊。如果您需要減少字元組,請參閱output.hashCharacters
[name]
:資產的檔案名稱,不含任何副檔名。
正斜線 /
可用於將檔案放置在子目錄中。使用函式時,assetInfo
是 generateBundle
中的一個精簡版本,不含 fileName
。另請參閱 output.chunkFileNames
、output.entryFileNames
。
output.banner/output.footer
類型 | 字串 | ((chunk: ChunkInfo) => 字串 | Promise<字串>) |
---|---|
CLI | --banner /--footer <文字> |
要加到套件前面的/後面的字串。您也可以提供一個傳回 Promise
的函式,以非同步方式產生它(注意:banner
和 footer
選項不會中斷原始碼對應)。
如果您提供一個函式,chunk
包含有關區塊的附加資訊,使用與 generateBundle
鉤子相同的 ChunkInfo
類型,但有下列差異
code
和map
未設定,因為區塊尚未呈現。- 所有包含雜湊的區塊檔案名稱都將包含雜湊佔位符。這包括
fileName
、imports
、importedBindings
、dynamicImports
和implicitlyLoadedBefore
。當您在從此選項傳回的程式碼中使用此類佔位符檔名或其一部分時,Rollup 會在generateBundle
之前將佔位符替換為實際雜湊,確保雜湊反映最終生成區塊的實際內容,包括所有引用的檔案雜湊。
chunk
是可變的,在此掛鉤中套用的變更將傳播到其他外掛程式和已生成的套件。這表示如果您在此掛鉤中新增或移除匯入或匯出,您應該更新 imports
、importedBindings
和/或 exports
。
// rollup.config.js
export default {
...,
output: {
...,
banner: '/* my-library version ' + version + ' */',
footer: '/* follow me on Twitter! @rich_harris */'
}
};
另請參閱 output.intro/output.outro
。
output.chunkFileNames
類型 | 字串 | ((chunkInfo: ChunkInfo) => 字串) |
---|---|
CLI | --chunkFileNames <模式> |
預設 | "[name]-[hash].js" |
用於命名程式碼分割時建立的共用區塊的模式,或每個區塊呼叫的函式,以傳回此類模式。模式支援下列佔位符
[format]
:輸出選項中定義的呈現格式,例如es
或cjs
。[hash]
:僅根據最終生成區塊的內容建立的雜湊,包括renderChunk
中的轉換和任何引用的檔案雜湊。您也可以透過例如[hash:10]
設定特定的雜湊長度。預設情況下,它將建立 base-64 雜湊。如果您需要減少字元組,請參閱output.hashCharacters
[name]
:區塊的名稱。這可以透過output.manualChunks
選項或透過外掛程式透過this.emitFile
建立區塊時明確設定。否則,它將從區塊內容中衍生。
正斜線 /
可用於將檔案放置在子目錄中。使用函式時,chunkInfo
是 generateBundle
中的一個精簡版本,沒有依賴檔案名稱的屬性,也沒有關於已呈現模組的資訊,因為呈現只會在產生檔案名稱後發生。不過,您可以存取包含的 moduleIds
清單。另請參閱 output.assetFileNames
、output.entryFileNames
。
output.compact
類型 | 布林值 |
---|---|
CLI | --compact /--no-compact |
預設 | false |
這將縮小 Rollup 產生的包裝器程式碼。請注意,這不會影響使用者撰寫的程式碼。此選項在綑綁預先縮小的程式碼時很有用。
output.dynamicImportInCjs
類型 | 布林值 |
---|---|
CLI | --dynamicImportInCjs /--no-dynamicImportInCjs |
預設 | true |
雖然 CommonJS 輸出原本只支援 require(…)
來匯入相依項,但最近的 Node 版本也開始支援 import(…)
,這是從 CommonJS 檔案匯入 ES 模組的唯一方式。如果此選項為 true
(預設值),Rollup 會將外部動態匯入保留為 CommonJS 輸出中的 import(…)
表達式。將其設定為 false
以使用 require(…)
語法改寫動態匯入。
// input
import('external').then(console.log);
// cjs output with dynamicImportInCjs: true or not set
import('external').then(console.log);
// cjs output with dynamicImportInCjs: false
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(
n,
k,
d.get
? d
: {
enumerable: true,
get: function () {
return e[k];
}
}
);
}
});
}
n.default = e;
return Object.freeze(n);
}
Promise.resolve()
.then(function () {
return /*#__PURE__*/ _interopNamespaceDefault(require('external'));
})
.then(console.log);
output.entryFileNames
類型 | 字串 | ((chunkInfo: ChunkInfo) => 字串) |
---|---|
CLI | --entryFileNames <pattern> |
預設 | "[name].js" |
用於從進入點建立的區塊的範本,或每進入區塊呼叫的函數,以傳回此類範本。範本支援下列的佔位符
[format]
:輸出選項中定義的呈現格式,例如es
或cjs
。[hash]
:僅根據最終產生的進入區塊內容的雜湊,包括renderChunk
中的轉換和任何引用的檔案雜湊。您也可以透過例如[hash:10]
設定特定的雜湊長度。預設情況下,它會建立一個 base-64 雜湊。如果您需要減少字元集,請參閱output.hashCharacters
[name]
:進入點的檔案名稱(不含副檔名),除非使用輸入的物件形式定義不同的名稱。
正斜線 /
可用於將檔案放置在子目錄中。使用函數時,chunkInfo
是 generateBundle
中的一個簡化版本,不含依賴於檔案名稱的屬性,且不含已呈現模組的資訊,因為呈現只會在產生檔案名稱後發生。不過,您可以存取包含的 moduleIds
清單。另請參閱 output.assetFileNames
、output.chunkFileNames
。
設定 output.preserveModules
選項時,此範本也會用於每個檔案。請注意,在此情況下,[name]
會包含從輸出根目錄的相對路徑,以及原始檔案副檔名(如果它不是 .js
、.jsx
、.mjs
、.cjs
、.ts
、.tsx
、.mts
或 .cts
之一)。
output.extend
類型 | 布林值 |
---|---|
CLI | --extend /--no-extend |
預設 | false |
是否在 umd
或 iife
格式中延伸由 name
選項定義的全局變數。當為 true
時,全局變數將定義為 (global.name = global.name || {})
。當為 false 時,由 name
定義的全局變數將被覆寫為 (global.name = {})
。
output.externalImportAttributes
類型 | 布林值 |
---|---|
CLI | --externalImportAttributes /--no-externalImportAttributes |
預設 | true |
如果輸出格式為 es
,是否將匯入屬性新增到輸出中的外部匯入。預設情況下,屬性會從輸入檔案取得,但外掛程式稍後可以新增或移除屬性。例如 import "foo" assert {type: "json"}
將導致相同的匯入出現在輸出中,除非選項設定為 false
。請注意,模組的所有匯入都需要有相符的屬性,否則會發出警告。
output.generatedCode
類型 | "es5" | "es2015"| { arrowFunctions?: boolean, constBindings?: boolean, objectShorthand?: boolean, preset?: "es5"| "es2015", reservedNamesAsProps?: boolean, symbols?: boolean } |
---|---|
CLI | --generatedCode <preset> |
預設 | "es5" |
Rollup 可以安全地在產生程式碼中使用的語言功能。這不會轉譯任何使用者程式碼,而只會變更 Rollup 在包裝函式和輔助函式中使用的程式碼。你可以選擇多個預設設定之一
"es5"
:不要使用箭頭函式等 ES2015+ 功能,但不要引用用作屬性的保留名稱。"es2015"
:使用任何高達 ES2015 的 JavaScript 功能。
output.generatedCode.arrowFunctions
類型 | 布林值 |
---|---|
CLI | --generatedCode.arrowFunctions /--no-generatedCode.arrowFunctions |
預設 | false |
是否為自動產生的程式碼片段使用箭頭函式。請注意,在某些地方(例如模組包裝函式),Rollup 將繼續使用括在括號中的常規函式,因為在某些 JavaScript 引擎中,這些函式將提供 明顯更好的效能。
output.generatedCode.constBindings
類型 | 布林值 |
---|---|
CLI | --generatedCode.constBindings /--no-generatedCode.constBindings |
預設 | false |
這會在某些地方和輔助函式中使用 const
而不是 var
。這會讓 Rollup 產生更有效率的輔助函式,因為區塊作用域的關係。
// input
export * from 'external';
// cjs output with constBindings: false
var external = require('external');
Object.keys(external).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return external[k];
}
});
});
// cjs output with constBindings: true
const external = require('external');
for (const k in external) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
Object.defineProperty(exports, k, {
enumerable: true,
get: () => external[k]
});
}
output.generatedCode.objectShorthand
類型 | 布林值 |
---|---|
CLI | --generatedCode.objectShorthand /--no-generatedCode.objectShorthand |
預設 | false |
當屬性名稱與值相符時,允許在物件中使用簡寫符號。
// input
const foo = 1;
export { foo, foo as bar };
// system output with objectShorthand: false
System.register('bundle', [], function (exports) {
'use strict';
return {
execute: function () {
const foo = 1;
exports({ foo: foo, bar: foo });
}
};
});
// system output with objectShorthand: true
System.register('bundle', [], function (exports) {
'use strict';
return {
execute: function () {
const foo = 1;
exports({ foo, bar: foo });
}
};
});
output.generatedCode.preset
類型 | "es5" | "es2015" |
---|---|
CLI | --generatedCode <值> |
允許選擇上面列出的其中一個預設值,同時覆寫一些選項。
export default {
// ...
output: {
generatedCode: {
preset: 'es2015',
arrowFunctions: false
}
// ...
}
};
output.generatedCode.reservedNamesAsProps
類型 | 布林值 |
---|---|
CLI | --generatedCode.reservedNamesAsProps /--no-generatedCode.reservedNamesAsProps |
預設 | true |
決定是否可以使用「default」等保留字作為屬性名稱,而不使用引號。這會讓產生的程式碼語法符合 ES3。不過請注意,若要完全符合 ES3,你可能還需要補充一些內建函式,例如 Object.keys
或 Array.prototype.forEach
。
// input
const foo = null;
export { foo as void };
// cjs output with reservedNamesAsProps: false
const foo = null;
exports['void'] = foo;
// cjs output with reservedNamesAsProps: true
const foo = null;
exports.void = foo;
output.generatedCode.symbols
類型 | 布林值 |
---|---|
CLI | --generatedCode.symbols /--no-generatedCode.symbols |
預設 | false |
是否允許在自動產生的程式碼片段中使用 Symbol
。目前,這只控制命名空間是否會將 Symbol.toStringTag
屬性設定為 Module
的正確值,這表示對於命名空間,String(namespace)
會記錄 [object Module]
。這會再次用於某些函式庫和架構中的功能偵測。
// input
export const foo = 42;
// cjs output with symbols: false
const foo = 42;
exports.foo = foo;
// cjs output with symbols: true
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const foo = 42;
exports.foo = foo;
output.hashCharacters
類型 | "base64" | "base32" | "hex" |
---|---|
CLI | --hashCharacters <name> |
預設 | "base64" |
這會決定 Rollup 允許在檔案雜湊中使用的字元集。
- 預設的
"base64"
會使用 url 安全的 base-64 雜湊,其潛在字元為ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
。 "base36"
只會使用小寫字母和數字abcdefghijklmnopqrstuvwxyz0123456789
。"hex"
會建立十六進位雜湊,其字元為abcdef0123456789
。
output.hoistTransitiveImports
類型 | 布林值 |
---|---|
CLI | --hoistTransitiveImports /--no-hoistTransitiveImports |
預設 | true |
預設情況下,在建立多個區塊時,進入區塊的傳遞式匯入會新增為進入區塊的空匯入。請參閱 "為什麼在進行程式碼拆分時,我的進入區塊中會出現其他匯入?",以取得詳細資訊和背景資料。將此選項設定為 false
會停用此行為。使用 output.preserveModules
選項時,會忽略此選項,因為在這種情況下,匯入永遠不會被提升。
output.inlineDynamicImports
類型 | 布林值 |
---|---|
CLI | --inlineDynamicImports /--no-inlineDynamicImports |
預設 | false |
這將內聯動態導入,而不是建立新的區塊來建立單一捆綁。僅在提供單一輸入時才有可能。請注意,這將變更執行順序:如果動態導入是內聯的,則僅動態導入的模組會立即執行。
output.interop
類型 | "compat" | "auto"| "esModule"| "default"| "defaultOnly"| ((id: string) => "compat"| "auto"| "esModule"| "default"| "defaultOnly") |
---|---|
CLI | --interop <value> |
預設 | "default" |
控制 Rollup 如何處理外部相依項中的預設、名稱空間和動態導入,這些相依項採用不原生支援這些概念的格式,例如 CommonJS。請注意,預設模式「default」模擬 NodeJS 行為,不同於 TypeScript esModuleInterop
。若要取得 TypeScript 的行為,請明確將值設定為 "auto"
。在範例中,我們將使用 CommonJS 格式,但 interop 的選擇也同樣適用於 AMD、IIFE 和 UMD 目標。
若要了解不同的值,假設我們正在為 cjs
目標捆綁下列程式碼
import ext_default, * as external from 'external1';
console.log(ext_default, external.bar, external);
import('external2').then(console.log);
請記住,對於 Rollup,import * as ext_namespace from 'external'; console.log(ext_namespace.bar);
完全等同於 import {bar} from 'external'; console.log(bar);
,並且會產生相同的程式碼。然而,在上述範例中,名稱空間物件本身也傳遞給全域函數,這表示我們需要它作為適當形成的物件。
"default"
假設所需值應視為導入模組的預設匯出,就像在 NodeJS 中從 ES 模組內容匯入 CommonJS 一樣。也支援命名匯入,這些匯入視為預設匯出的屬性。若要建立名稱空間物件,Rollup 會注入這些輔助程式jsvar external = require('external1'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty( n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } } ); } }); } n.default = e; return Object.freeze(n); } var external__namespace = /*#__PURE__*/ _interopNamespaceDefault(external); console.log(external, external__namespace.bar, external__namespace); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespaceDefault(require('external2')); }) .then(console.log);
"esModule"
假設必要的模組是轉譯的 ES 模組,其中必要的數值對應至模組名稱空間,而預設的匯出是匯出物件的.default
屬性。這是唯一不會注入任何輔助函式的互操作類型jsvar external = require('external1'); console.log(external.default, external.bar, external); Promise.resolve() .then(function () { return require('external2'); }) .then(console.log);
當使用
esModule
時,Rollup 沒有新增任何額外的互操作輔助程式,且也支援預設匯出的即時繫結。"auto"
結合了"esModule"
和"default"
,透過注入輔助程式,其中包含在執行時期偵測必要的數值是否包含__esModule
屬性 的程式碼。新增此屬性是一種由 TypeScriptesModuleInterop
、Babel 和其他工具實作的駭客手法,用來表示必要的數值是轉譯 ES 模組的名稱空間。jsvar external = require('external1'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty( n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } } ); } }); } n.default = e; return Object.freeze(n); } var external__namespace = /*#__PURE__*/ _interopNamespace(external); console.log( external__namespace.default, external__namespace.bar, external__namespace ); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespace(require('external2')); }) .then(console.log);
請注意 Rollup 如何重複使用已建立的名稱空間物件來取得
default
匯出。如果不需要名稱空間物件,Rollup 會使用更簡單的輔助程式js// input import ext_default from 'external'; console.log(ext_default); // output var ext_default = require('external'); function _interopDefault(e) { return e && e.__esModule ? e : { default: e }; } var ext_default__default = /*#__PURE__*/ _interopDefault(ext_default); console.log(ext_default__default.default);
compat
等同於"auto"
,但它使用略微不同的輔助程式來取得預設的匯出,它會檢查default
屬性而不是__esModule
屬性的存在。除了在罕見的情況下,CommonJS 模組匯出一個不應為預設匯出的"default"
屬性,這通常有助於讓互操作「正常運作」,因為它不依賴於特殊駭客手法,而是使用鴨子型別jsvar external = require('external1'); function _interopNamespaceCompat(e) { if (e && typeof e === 'object' && 'default' in e) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty( n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } } ); } }); } n.default = e; return Object.freeze(n); } var external__namespace = /*#__PURE__*/ _interopNamespaceCompat(external); console.log( external__namespace.default, external__namespace.bar, external__namespace ); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespaceCompat(require('external2')); }) .then(console.log);
類似於
"auto"
,如果不需要名稱空間,Rollup 會使用更簡單的輔助程式js// input import ext_default from 'external'; console.log(ext_default); // output var ext_default = require('external'); function _interopDefaultCompat(e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } var ext_default__default = /*#__PURE__*/ _interopDefaultCompat(ext_default); console.log(ext_default__default.default);
"defaultOnly"
類似於"default"
,但有以下例外- 禁止命名匯入。如果遇到此類匯入,Rollup 會擲回錯誤,即使在
es
和system
格式中也是如此。這樣可以確保程式碼的es
版本能夠正確地匯入 Node 中非內建的 CommonJS 模組。 - 雖然名稱空間重新匯出
export * from 'external';
沒有被禁止,但它們會被忽略,並且會導致 Rollup 顯示警告,因為如果沒有命名匯出,它們不會產生任何效果。 - 當命名空間物件產生時,Rollup 會使用更簡單的輔助程式。
以下是 Rollup 會從範例程式碼建立的內容。請注意,我們從程式碼中移除
external.bar
,否則 Rollup 會傳回錯誤,因為如前所述,這等於命名匯入。jsvar ext_default = require('external1'); function _interopNamespaceDefaultOnly(e) { return Object.freeze({ __proto__: null, default: e }); } var ext_default__namespace = /*#__PURE__*/ _interopNamespaceDefaultOnly(ext_default); console.log(ext_default, ext_default__namespace); Promise.resolve() .then(function () { return /*#__PURE__*/ _interopNamespaceDefaultOnly( require('external2') ); }) .then(console.log);
- 禁止命名匯入。如果遇到此類匯入,Rollup 會擲回錯誤,即使在
當提供函式時,Rollup 會將每個外部 ID 傳遞給此函式一次,以控制每個依賴項的互操作類型。
例如,如果所有依賴項都是 CommonJs,下列設定會確保命名匯入僅允許來自 Node 內建程式
js// rollup.config.js import builtins from 'builtins'; const nodeBuiltins = new Set(builtins()); export default { // ... output: { // ... interop(id) { if (nodeBuiltins.has(id)) { return 'default'; } return 'defaultOnly'; } } };
有些其他選項會影響產生的互操作程式碼
- 將
output.externalLiveBindings
設定為false
會產生簡化的命名空間輔助程式,以及簡化提取預設匯入的程式碼。 - 將
output.freeze
設定為false
會防止產生的互操作命名空間物件被凍結。
output.intro/output.outro
類型 | 字串 | ((chunk: ChunkInfo) => 字串 | Promise<字串>) |
---|---|
CLI | --intro /--outro <text> |
類似於 output.banner/output.footer
,但程式碼會進入任何格式特定的包裝器內部。
export default {
//...,
output: {
//...,
intro: 'const ENVIRONMENT = "production";'
}
};
output.manualChunks
類型 | { [chunkAlias: string]: string[] } | ((id: string, {getModuleInfo, getModuleIds}) => string | void) |
---|
允許建立自訂共用共用區塊。使用物件格式時,每個屬性都代表一個區塊,其中包含列出的模組及其所有依賴項(如果它們是模組圖形的一部分),除非它們已在另一個手動區塊中。區塊的名稱將由屬性金鑰決定。
請注意,列出的模組本身不必是模組圖形的一部分,如果您使用 @rollup/plugin-node-resolve
並從套件使用深度匯入,這會很有用。例如
({
manualChunks: {
lodash: ['lodash']
}
});
即使你只使用 import get from 'lodash/get'
形式的導入,也會將所有 lodash 模組放入手動區塊。
使用函式形式時,每個解析的模組 ID 都會傳遞給函式。如果傳回字串,模組及其所有相依項將會使用指定的區塊名稱新增到手動區塊。例如,這將建立一個包含 node_modules
內部所有相依項的 vendor
區塊
function manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor';
}
}
請注意,如果在實際使用對應模組之前觸發了副作用,手動區塊可能會改變應用程式的行為。
使用函式形式時,manualChunks
會傳遞一個物件作為第二個參數,其中包含函式 getModuleInfo
和 getModuleIds
,其運作方式與外掛程式內容中的 this.getModuleInfo
和 this.getModuleIds
相同。
這可以用於根據模組在模組圖中的位置,動態決定將模組放入哪個手動區塊。例如,考慮一個場景,其中你有一組元件,每個元件動態導入一組已翻譯的字串,即
// Inside the "foo" component
function getTranslatedStrings(currentLanguage) {
switch (currentLanguage) {
case 'en':
return import('./foo.strings.en.js');
case 'de':
return import('./foo.strings.de.js');
// ...
}
}
如果大量此類元件一起使用,這將導致大量非常小的區塊動態導入:即使我們知道由同一個區塊導入的相同語言的所有語言檔案將始終一起使用,但 Rollup 沒有此資訊。
以下程式碼將合併僅由單一進入點使用的相同語言的所有檔案
function manualChunks(id, { getModuleInfo }) {
const match = /.*\.strings\.(\w+)\.js/.exec(id);
if (match) {
const language = match[1]; // e.g. "en"
const dependentEntryPoints = [];
// we use a Set here so we handle each module at most once. This
// prevents infinite loops in case of circular dependencies
const idsToHandle = new Set(getModuleInfo(id).dynamicImporters);
for (const moduleId of idsToHandle) {
const { isEntry, dynamicImporters, importers } =
getModuleInfo(moduleId);
if (isEntry || dynamicImporters.length > 0)
dependentEntryPoints.push(moduleId);
// The Set iterator is intelligent enough to iterate over
// elements that are added during iteration
for (const importerId of importers) idsToHandle.add(importerId);
}
// If there is a unique entry, we put it into a chunk based on the
// entry name
if (dependentEntryPoints.length === 1) {
return `${
dependentEntryPoints[0].split('/').slice(-1)[0].split('.')[0]
}.strings.${language}`;
}
// For multiple entries, we put it into a "shared" chunk
if (dependentEntryPoints.length > 1) {
return `shared.strings.${language}`;
}
}
}
output.minifyInternalExports
類型 | 布林值 |
---|---|
CLI | --minifyInternalExports /--no-minifyInternalExports |
預設 | es 和 system 格式為 true ,或如果 output.compact 為 true ,否則為 false |
預設情況下,對於 es
和 system
格式或如果 output.compact
為 true
,Rollup 會嘗試將內部變數匯出為單字母變數,以利於更好的縮小。
範例
輸入
// main.js
import './lib.js';
// lib.js
import('./dynamic.js');
export const importantValue = 42;
// dynamic.js
import { importantValue } from './lib.js';
console.log(importantValue);
輸出,其中 output.minifyInternalExports: true
// main.js
import './main-5532def0.js';
// main-5532def0.js
import('./dynamic-402de2f0.js');
const importantValue = 42;
export { importantValue as i };
// dynamic-402de2f0.js
import { i as importantValue } from './main-5532def0.js';
console.log(importantValue);
輸出,其中 output.minifyInternalExports: false
// main.js
import './main-5532def0.js';
// main-5532def0.js
import('./dynamic-402de2f0.js');
const importantValue = 42;
export { importantValue };
// dynamic-402de2f0.js
import { importantValue } from './main-5532def0.js';
console.log(importantValue);
即使看起來將此選項設定為 true
會使輸出變大,但如果使用縮小器,它實際上會使輸出變小。在這種情況下,export { importantValue as i }
可以變成例如 export{a as i}
甚至 export{i}
,而否則它會產生 export{ a as importantValue }
,因為縮小器通常不會變更匯出簽章。
output.paths
類型 | { [id: 字串]: 字串 } | ((id: 字串) => 字串) |
---|
將外部模組 ID 對應至路徑。外部 ID 是 無法解析 的 ID,或由 external
選項明確提供的 ID。output.paths
提供的路徑將用於產生的套件中,而不是模組 ID,例如,這允許您從 CDN 載入依賴項
// app.js
import { selectAll } from 'd3';
selectAll('p').style('color', 'purple');
// ...
// rollup.config.js
export default {
input: 'app.js',
external: ['d3'],
output: {
file: 'bundle.js',
format: 'amd',
paths: {
d3: 'https://d3.dev.org.tw/d3.v4.min'
}
}
};
// bundle.js
define(['https://d3.dev.org.tw/d3.v4.min'], function (d3) {
d3.selectAll('p').style('color', 'purple');
// ...
});
output.preserveModules
類型 | 布林值 |
---|---|
CLI | --preserveModules /--no-preserveModules |
預設 | false |
此模式不會建立儘可能少的區塊,而是會使用原始模組名稱作為檔案名稱,為所有模組建立個別區塊。需要 output.dir
選項。仍然會套用 tree-shaking,抑制未由提供的進入點使用的檔案,或在執行時沒有副作用的檔案,以及移除不是進入點的檔案中未使用的匯出。另一方面,如果外掛程式(例如 @rollup/plugin-commonjs
)發射額外的「虛擬」檔案以達成某些結果,那些檔案將使用模式 _virtual/fileName.js
作為實際檔案發射。
因此,如果您想要直接從這些檔案匯入,但預期的匯出項可能遺失,建議不要盲目使用此選項將整個檔案結構轉換為另一種格式。在這種情況下,您應該將所有檔案明確指定為進入點,方法是將它們新增到 input
選項物件,請參閱範例了解如何執行此操作。
請注意,當轉換為 cjs
或 amd
格式時,預設會將每個檔案視為進入點,並將 output.exports
設定為 auto
。這表示,例如對於 cjs
,只包含預設匯出項的檔案會呈現為
// input main.js
export default 42;
// output main.js
('use strict');
var main = 42;
module.exports = main;
直接將值指定給 module.exports
。如果有人匯入此檔案,他們將透過以下方式取得預設匯出項
const main = require('./main.js');
console.log(main); // 42
與一般進入點一樣,混合使用預設和命名匯出項的檔案會產生警告。您可以透過 output.exports: "named"
強制所有檔案使用命名匯出模式來避免警告。在這種情況下,預設匯出項需要透過匯出項的 .default
屬性來存取
// input main.js
export default 42;
// output main.js
('use strict');
Object.defineProperty(exports, '__esModule', { value: true });
var main = 42;
exports.default = main;
// consuming file
const main = require('./main.js');
console.log(main.default); // 42
output.preserveModulesRoot
類型 | 字串 |
---|---|
CLI | --preserveModulesRoot <directory-name> |
輸入模組的目錄路徑,當 output.preserveModules
為 true
時,應從 output.dir
路徑中移除。
例如,根據下列設定
export default {
input: ['src/module.js', `src/another/module.js`],
output: [
{
format: 'es',
dir: 'dist',
preserveModules: true,
preserveModulesRoot: 'src'
}
]
};
preserveModulesRoot
設定可確保輸入模組會輸出到路徑 dist/module.js
和 dist/another/module.js
。
此選項在使用外掛程式(例如 @rollup/plugin-node-resolve
)時特別有用,因為這些外掛程式可能會變更輸出目錄結構。這可能會發生在未將第三方模組標記為 external
時,或在開發依賴彼此且未標記為 external
的多個套件的單一存放區時。
output.sourcemap
類型 | 布林值 | 'inline'| 'hidden' |
---|---|
CLI | -m /--sourcemap /--no-sourcemap |
預設 | false |
如果為 true
,將會建立一個獨立的 sourcemap 檔案。如果為 "inline"
,sourcemap 將會附加到結果的 output
檔案中,作為資料 URI。"hidden"
的運作方式與 true
相同,但會抑制已套件檔案中的對應 sourcemap 註解。
output.sourcemapBaseUrl
類型 | 字串 |
---|---|
CLI | --sourcemapBaseUrl <網址> |
預設情況下,Rollup 所產生的 sourcemap 檔案會使用相對網址來參照它們所描述的檔案。透過提供一個絕對基本網址,例如 https://example.com
,sourcemap 將會改用絕對網址。
output.sourcemapExcludeSources
類型 | 布林值 |
---|---|
CLI | --sourcemapExcludeSources /--no-sourcemapExcludeSources |
預設 | false |
如果為 true
,sourcemap 中不會加入來源的實際程式碼,這會讓 sourcemap 的大小大幅縮小。
output.sourcemapFile
類型 | 字串 |
---|---|
CLI | --sourcemapFile <帶有路徑的檔案名稱> |
已產生套件的位置。如果這是絕對路徑,sourcemap 中的所有 sources
路徑都會相對於該路徑。map.file
屬性是 sourcemapFile
的基本檔名,因為假設 sourcemap 的位置與套件相鄰。
如果已指定 output
,則不需要 sourcemapFile
,這種情況下會透過將「.map」加到套件的輸出檔名來推斷輸出檔名。
output.sourcemapFileNames
類型 | 字串 | ((chunkInfo: ChunkInfo) => 字串) |
---|---|
CLI | --sourcemapFileNames <樣式> |
用於原始碼地圖的模式,或呼叫每個原始碼地圖以傳回此類模式的函數。模式支援下列佔位符
[format]
:輸出選項中定義的呈現格式,例如es
或cjs
。[hash]
:僅根據最終產生的原始碼地圖內容的雜湊。您也可以透過例如[hash:10]
設定特定雜湊長度。預設情況下,它會建立一個 base-64 雜湊。如果您需要縮減字元集,請參閱output.hashCharacters
[chunkhash]
:與對應產生的區塊 (如果有的話) 使用的雜湊相同。[name]
:進入點的檔案名稱(不含副檔名),除非使用輸入的物件形式定義不同的名稱。
正斜線 /
可用於將檔案放置在子目錄中。使用函數時,chunkInfo
是 generateBundle
中的一個簡化版本,不含依賴於檔案名稱的屬性,且不含已呈現模組的資訊,因為呈現只會在產生檔案名稱後發生。不過,您可以存取包含的 moduleIds
清單。另請參閱 output.assetFileNames
、output.chunkFileNames
。
output.sourcemapIgnoreList
類型 | 布林值 | (relativeSourcePath: 字串, sourcemapPath: 字串) => 布林值 |
---|
一個謂詞,用於決定是否忽略原始碼地圖中的原始碼檔案,用於填入 x_google_ignoreList
原始碼地圖擴充功能。relativeSourcePath
是從產生的 .map
檔案到對應原始碼檔案的相對路徑,而 sourcemapPath
是產生的原始碼地圖檔案的完整解析路徑。
import path from 'node:path';
export default {
input: 'src/main',
output: [
{
file: 'bundle.js',
sourcemapIgnoreList: (relativeSourcePath, sourcemapPath) => {
// will ignore-list all files with node_modules in their paths
return relativeSourcePath.includes('node_modules');
},
format: 'es',
sourcemap: true
}
]
};
當您未明確指定此選項時,預設情況下,它會將路徑中包含 node_modules
的所有檔案放入忽略清單中。您可以在此處指定 false
以完全關閉忽略清單。
output.sourcemapPathTransform
類型 | (relativeSourcePath: 字串, sourcemapPath: 字串) => 字串 |
---|
套用至原始碼地圖中每個路徑的轉換。relativeSourcePath
是從產生的 .map
檔案到對應原始碼檔案的相對路徑,而 sourcemapPath
是產生的原始碼地圖檔案的完整解析路徑。
import path from 'node:path';
export default {
input: 'src/main',
output: [
{
file: 'bundle.js',
sourcemapPathTransform: (relativeSourcePath, sourcemapPath) => {
// will replace relative paths with absolute paths
return path.resolve(
path.dirname(sourcemapPath),
relativeSourcePath
);
},
format: 'es',
sourcemap: true
}
]
};
output.validate
類型 | 布林值 |
---|---|
CLI | --validate /--no-validate |
預設 | false |
重新解析每個產生的區塊,以偵測產生的程式碼是否為有效的 JavaScript。這對於除錯由使用 renderChunk
鉤子來轉換程式碼的外掛所產生的輸出很有用。
如果程式碼無效,會發出警告。請注意,並未擲回任何錯誤,因此您仍可以檢查產生的輸出。若要將此警告提升為錯誤,您可以在 onwarn
處理常式中監控它。
preserveEntrySignatures
類型 | "strict" | "allow-extension" | "exports-only"| false |
---|---|
CLI | --preserveEntrySignatures <strict | allow-extension> /--no-preserveEntrySignatures |
預設 | "exports-only" |
控制 Rollup 是否嘗試確保入口區塊與基礎入口模組具有相同的匯出。
- 如果設定為
"strict"
,Rollup 會在入口區塊中建立與對應入口模組中完全相同的匯出。如果無法執行此操作,因為需要將其他內部匯出新增至區塊,Rollup 會建立一個「門面」入口區塊,僅重新匯出其他區塊中必要的繫結,但本身不包含任何程式碼。這是建議用於函式庫的設定。 "allow-extension"
會在入口區塊中建立入口模組的所有匯出,但必要時也可能會新增其他匯出,避免建立「門面」入口區塊。此設定適用於不需要嚴格簽章的函式庫。- 如果入口模組有匯出,
"exports-only"
會像"strict"
一樣運作,否則會像"allow-extension"
一樣運作。 false
不會將任何入口模組的匯出新增至對應的區塊,甚至不會包含對應的程式碼,除非這些匯出在套件中的其他地方使用。不過,可能會將內部匯出新增至入口區塊。這是建議用於入口區塊會放置在腳本標籤中的網路應用程式的設定,因為它可能會減少區塊數和套件大小。
範例
輸入
// main.js
import { shared } from './lib.js';
export const value = `value: ${shared}`;
import('./dynamic.js');
// lib.js
export const shared = 'shared';
// dynamic.js
import { shared } from './lib.js';
console.log(shared);
preserveEntrySignatures: "strict"
的輸出
// main.js
export { v as value } from './main-50a71bb6.js';
// main-50a71bb6.js
const shared = 'shared';
const value = `value: ${shared}`;
import('./dynamic-cd23645f.js');
export { shared as s, value as v };
// dynamic-cd23645f.js
import { s as shared } from './main-50a71bb6.js';
console.log(shared);
preserveEntrySignatures: "allow-extension"
的輸出
// main.js
const shared = 'shared';
const value = `value: ${shared}`;
import('./dynamic-298476ec.js');
export { shared as s, value };
// dynamic-298476ec.js
import { s as shared } from './main.js';
console.log(shared);
preserveEntrySignatures: false
的輸出
// main.js
import('./dynamic-39821cef.js');
// dynamic-39821cef.js
const shared = 'shared';
console.log(shared);
目前,覆寫個別輸入區塊此設定的唯一方法是使用外掛 API,並透過 this.emitFile
發出這些區塊,而非使用 input
選項。
strictDeprecations
類型 | 布林值 |
---|---|
CLI | --strictDeprecations /--no-strictDeprecations |
預設 | false |
啟用此旗標時,Rollup 會在使用已棄用功能時擲回錯誤,而非顯示警告。此外,標記為在下一主要版本中會收到棄用警告的功能,在使用時也會擲回錯誤。
此旗標的用意是讓例如外掛作者能盡早調整其外掛以符合即將推出的主要版本。
危險區域
除非您知道自己在做什麼,否則可能不需要使用這些選項!
context
類型 | 字串 |
---|---|
CLI | --context <contextVariable> |
預設 | 未定義 |
預設情況下,模組的內容(即頂層的 this
值)為 undefined
。在少數情況下,您可能需要將其變更為其他值,例如 'window'
。
moduleContext
類型 | ((id: string) => string) | { [id: string]: string } |
---|
與 context
相同,但為每個模組,可以是 id: context
成對的物件,或 id => context
函式。
output.amd
類型 | { id?: string, autoId?: boolean, basePath?: string, define?: string } |
---|
注意 id
僅能用於單一檔案建置,且無法與 autoId
/basePath
結合使用。
output.amd.id
類型 | 字串 |
---|---|
CLI | --amd.id <amdId> |
用於 AMD/UMD 捆綁的 ID
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
id: 'my-bundle'
}
};
// -> define('my-bundle', ['dependency'], ...
output.amd.autoId
類型 | 布林值 |
---|---|
CLI | --amd.autoId |
將 ID 設為區塊 ID(移除 '.js' 副檔名)。
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
autoId: true
}
};
// -> define('main', ['dependency'], ...
// -> define('dynamic-chunk', ['dependency'], ...
output.amd.basePath
類型 | 字串 |
---|---|
CLI | --amd.basePath |
將預先附加至自動產生 ID 的路徑。如果建置將置於另一個 AMD 專案中,且不在根目錄下,這會很有用。
僅與 output.amd.autoId
有效。
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
autoId: true,
basePath: 'some/where'
}
};
// -> define('some/where/main', ['dependency'], ...
// -> define('some/where/dynamic-chunk', ['dependency'], ...
output.amd.define
類型 | 字串 |
---|---|
CLI | --amd.define <defineFunctionName> |
用於取代 define
的函數名稱
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
define: 'def'
}
};
// -> def(['dependency'],...
output.amd.forceJsExtensionForImports
類型 | 布林值 |
---|---|
CLI | --amd.forceJsExtensionForImports |
預設 | false |
為已產生區塊和本機 AMD 模組的匯入項目加入 .js
副檔名
// rollup.config.js
export default {
...,
format: 'amd',
amd: {
forceJsExtensionForImports: true
}
};
// -> define(['./chunk-or-local-file.js', 'dependency', 'third/dependency'],...
output.esModule
類型 | 布林值 | "if-default-prop" |
---|---|
CLI | --esModule /--no-esModule |
預設 | "if-default-prop" |
在為非 ES 格式產生匯出項目時,是否加入 __esModule: true
屬性。此屬性表示匯出的值是 ES 模組的命名空間,且此模組的預設匯出項目對應至匯出物件的 .default
屬性。
true
在使用 命名匯出模式 時,將永遠加入屬性,這與其他工具的做法類似。"if-default-prop"
僅會在使用命名匯出模式且也有預設匯出時新增屬性。細微的差異在於,如果沒有預設匯出,您的函式庫的 CommonJS 版本的使用者會將所有命名匯出當作預設匯出,而不是錯誤或undefined
。我們選擇將此設為預設值,因為__esModule
屬性並非任何 JavaScript 執行時間所遵循的標準,而且會導致許多互操作性問題,所以我們希望將其使用限制在真正需要的情況。- 另一方面,
false
永遠不會新增屬性,即使預設匯出會變成屬性.default
。
另請參閱 output.interop
。
output.exports
類型 | "auto" | "default"| "named"| "none" |
---|---|
CLI | --exports <exportMode> |
預設 | 'auto' |
要使用的匯出模式。預設為 auto
,它會根據 input
模組匯出什麼來猜測您的意圖
default
– 如果您僅使用export default ...
匯出一項內容;請注意,這可能會在產生 CommonJS 輸出時造成問題,而 CommonJS 輸出應可與 ESM 輸出互換,請參閱下方named
– 如果您使用命名匯出none
– 如果您沒有匯出任何內容(例如,您正在建置應用程式,而不是函式庫)
由於這僅為輸出轉換,因此您只能在預設匯出是所有輸入區塊的唯一匯出時選擇 default
。同樣地,您只能在沒有匯出的情況下選擇 none
,否則 Rollup 會擲回錯誤。
default
和 named
之間的差異會影響其他人如何使用您的套件。如果您使用 default
,CommonJS 使用者可以執行下列動作
// your-lib package entry
export default 'Hello world';
// a CommonJS consumer
/* require( "your-lib" ) returns "Hello World" */
const hello = require('your-lib');
使用 named
時,使用者會執行下列動作
// your-lib package entry
export const hello = 'Hello world';
// a CommonJS consumer
/* require( "your-lib" ) returns {hello: "Hello World"} */
const hello = require('your-lib').hello;
/* or using destructuring */
const { hello } = require('your-lib');
問題在於,如果您使用 named
匯出,但也有default
匯出,使用者必須執行類似下列動作才能使用預設匯出
// your-lib package entry
export default 'foo';
export const bar = 'bar';
// a CommonJS consumer
/* require( "your-lib" ) returns {default: "foo", bar: "bar"} */
const foo = require('your-lib').default;
const bar = require('your-lib').bar;
/* or using destructuring */
const { default: foo, bar } = require('your-lib');
注意:有一些工具(例如 Babel、TypeScript、Webpack 和 @rollup/plugin-commonjs
)能夠使用 ES 模組解析 CommonJS require(...)
呼叫。如果您要產生 CommonJS 輸出,而該輸出旨在與這些工具的 ESM 輸出互換,則您應始終使用 named
匯出模式。原因是這些工具大多數會在 require
上傳回 ES 模組的命名空間,而預設匯出是 .default
屬性。
換句話說,對於這些工具,您無法建立一個封裝介面,其中 const lib = require("your-lib")
產生與 import lib from "your-lib"
相同的結果。然而,使用命名匯出模式時,const {lib} = require("your-lib")
將等於 import {lib} from "your-lib"
。
output.externalLiveBindings
類型 | 布林值 |
---|---|
CLI | --externalLiveBindings /--no-externalLiveBindings |
預設 | true |
設為 false
時,Rollup 將不會產生支援外部匯入的動態繫結的程式碼,而是假設匯出不會隨時間而變更。這將使 Rollup 能夠產生更最佳化的程式碼。請注意,當涉及外部依賴項的循環依賴項時,這可能會造成問題。
這將避免 Rollup 在程式碼中產生 getter 的大多數情況,因此在許多情況下可用於使程式碼與 IE8 相容。
範例
// input
export { x } from 'external';
// CJS output with externalLiveBindings: true
var external = require('external');
Object.defineProperty(exports, 'x', {
enumerable: true,
get: function () {
return external.x;
}
});
// CJS output with externalLiveBindings: false
var external = require('external');
exports.x = external.x;
output.freeze
類型 | 布林值 |
---|---|
CLI | --freeze /--no-freeze |
預設 | true |
是否對動態存取的命名空間匯入物件(例如 import * as namespaceImportObject from...
)執行 Object.freeze()
。
output.indent
類型 | 布林值 | 字串 |
---|---|
CLI | --indent /--no-indent |
預設 | true |
對於需要縮排程式碼的格式(amd
、iife
、umd
、system
),要使用的縮排字串。也可以是 false
(不縮排)或 true
(預設值 – 自動縮排)
// rollup.config.js
export default {
...,
output: {
...,
indent: false
}
};
output.noConflict
類型 | 布林值 |
---|---|
CLI | --noConflict /--no-noConflict |
預設 | false |
這會為 UMD 捆綁產生一個額外的 noConflict
匯出。在 IIFE 場景中呼叫時,此方法會傳回捆綁匯出,同時將對應的全球變數還原為其先前值。
output.reexportProtoFromExternal
類型 | 布林值 |
---|---|
CLI | --reexportProtoFromExternal /--no-reexportProtoFromExternal |
預設 | true |
此選項僅在 output.format
設為 ['amd', 'cjs', 'iife', 'umd']
之一,且 output.externalLiveBindings
設為 false 時才有效。
為了達到最大的相容性,預設情況下,Rollup 會從外部模組重新匯出 __proto__
。然而,對於常見的使用案例,強烈建議將此值設為 false,因為這樣可以有效地減少輸出大小。
// the input file
export * from 'rollup';
// the output file if the output.format is cjs
'use strict';
// reexportProtoFromExternal is true
var rollup = require('rollup');
Object.prototype.hasOwnProperty.call(rollup, '__proto__') &&
!Object.prototype.hasOwnProperty.call(exports, '__proto__') &&
Object.defineProperty(exports, '__proto__', {
enumerable: true,
value: rollup['__proto__']
});
Object.keys(rollup).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
exports[k] = rollup[k];
});
// reexportProtoFromExternal is false
var rollup = require('rollup');
Object.keys(rollup).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k))
exports[k] = rollup[k];
});
output.sanitizeFileName
類型 | 布林值 | (字串) => 字串 |
---|---|
CLI | --sanitizeFileName /no-sanitizeFileName |
預設 | true |
設為 false
以停用所有區塊名稱的消毒(移除 \0
、?
和 *
字元)。
或者,設為函式以允許自訂區塊名稱的消毒。
output.strict
類型 | 布林值 |
---|---|
CLI | --strict /--no-strict |
預設 | true |
是否在產生的非 ES 捆綁的最上方包含 'use strict' 指令。嚴格來說,ES 模組永遠處於嚴格模式,因此,沒有充分的理由,不應停用此功能。
output.systemNullSetters
類型 | 布林值 |
---|---|
CLI | --systemNullSetters /--no-systemNullSetters |
預設 | true |
輸出 system
模組格式時,預設情況下,空設定函式會以 null
取代,作為輸出簡化。這與 SystemJS v6.3.3 之前版本不相容。停用此選項以輸出較舊的 SystemJS 版本支援的空函式。
preserveSymlinks
類型 | 布林值 |
---|---|
CLI | --preserveSymlinks |
預設 | false |
設為 false
時,解析檔案時會追蹤符號連結。設為 true
時,符號連結會視為檔案位於連結處,而不是追蹤連結。以下情況說明此概念
// /main.js
import { x } from './linked.js';
console.log(x);
// /linked.js
// this is a symbolic link to /nested/file.js
// /nested/file.js
export { x } from './dep.js';
// /dep.js
export const x = 'next to linked';
// /nested/dep.js
export const x = 'next to original';
如果 preserveSymlinks
為 false
,則從 /main.js
建立的套件會記錄「next to original」,因為它會使用符號連結檔案的位置來解析其依賴項。但是,如果 preserveSymlinks
為 true
,則會記錄「next to linked」,因為符號連結不會解析。
shimMissingExports
類型 | 布林值 |
---|---|
CLI | --shimMissingExports /--no-shimMissingExports |
預設 | false |
如果提供此選項,則從未定義這些繫結的檔案匯入繫結時,套件處理不會失敗。相反地,會為這些繫結建立新的變數,其值為 undefined
。
treeshake
類型 | 布林值 | TreeshakingPreset | TreeshakingOptions |
---|---|
CLI | --treeshake /--no-treeshake |
預設 | true |
type TreeshakingPreset = 'smallest' | 'safest' | 'recommended';
interface TreeshakingOptions {
annotations?: boolean;
correctVarValueBeforeDeclaration?: boolean;
moduleSideEffects?: ModuleSideEffectsOption;
preset?: TreeshakingPreset;
propertyReadSideEffects?: boolean | 'always';
tryCatchDeoptimization?: boolean;
unknownGlobalSideEffects?: boolean;
}
type ModuleSideEffectsOption =
| boolean
| 'no-external'
| string[]
| HasModuleSideEffects;
type HasModuleSideEffects = (id: string, external: boolean) => boolean;
是否套用樹狀搖晃,以及微調樹狀搖晃處理。將此選項設為 false
會產生較大的套件,但可能會改善建置效能。您也可以選擇三個預設值之一,如果新增新的選項,這些預設值會自動更新
"smallest"
將為您選擇選項值,以盡可能地縮小輸出大小。只要您不依賴於某些模式,這應適用於大多數程式碼庫,這些模式目前為- 具有副作用的 getter 僅在使用回傳值時才會保留 (
treeshake.propertyReadSideEffects: false
) - 僅當使用至少一個匯出的值時,才會保留來自匯入模組的程式碼 (
treeshake.moduleSideEffects: false
) - 您不應捆綁依賴於偵測損壞內建函式的多重填充 (
treeshake.tryCatchDeoptimization: false
) - 某些語意問題可能會被吞掉 (
treeshake.unknownGlobalSideEffects: false
,treeshake.correctVarValueBeforeDeclaration: false
)
- 具有副作用的 getter 僅在使用回傳值時才會保留 (
"recommended"
應適用於大多數使用模式。不過,某些語意問題可能會被吞掉 (treeshake.unknownGlobalSideEffects: false
,treeshake.correctVarValueBeforeDeclaration: false
)"safest"
嘗試盡可能符合規格,同時仍提供一些基本的 tree-shaking 功能。true
等同於未指定選項,並且將永遠選擇預設值 (請參閱下方)。
如果您發現由 tree-shaking 演算法造成的錯誤,請提交問題!將此選項設定為物件表示已啟用 tree-shaking,並授予下列其他選項
treeshake.annotations
類型 | 布林值 |
---|---|
CLI | --treeshake.annotations /--no-treeshake.annotations |
預設 | true |
如果為 false
,則忽略註解中提示的提示
@__PURE__
包含 @__PURE__
或 #__PURE__
的註解將特定函式呼叫或建構函式呼叫標記為沒有副作用。這表示 Rollup 會執行 tree-shake,也就是移除呼叫,除非回傳值用於未執行 tree-shake 的某些程式碼中。這些註解需要緊接在呼叫呼叫之前才能生效。除非將此選項設定為 false
,否則以下程式碼將完全執行 tree-shake,否則程式碼將保持不變。
/*@__PURE__*/ console.log('side-effect');
class Impure {
constructor() {
console.log('side-effect');
}
}
/*@__PURE__ There may be additional text in the comment */ new Impure();
此類註解會被視為 有效,如果它緊接在函式呼叫或建構函式呼叫之前,且僅以空白或註解與被呼叫者分隔。唯一的例外是包住呼叫或呼叫的括號。
無效註解會被移除,而 Rollup 會發出警告。有效註解會保留在程式碼中,除非其函式呼叫或建構函式呼叫也已移除。
@__NO_SIDE_EFFECTS__
包含 @__NO_SIDE_EFFECTS__
或 #__NO_SIDE_EFFECTS__
的註解將函式宣告本身標記為沒有副作用。當函式已標記為沒有副作用時,對該函式的所有呼叫都將被視為沒有副作用。除非將此選項設定為 false
,否則以下程式碼將完全執行 tree-shake,否則程式碼將保持不變。
/*@__NO_SIDE_EFFECTS__*/
function impure() {
console.log('side-effect');
}
/*@__NO_SIDE_EFFECTS__*/
const impureArrowFn = () => {
console.log('side-effect');
};
impure(); // <-- call will be considered as side effect free
impureArrowFn(); // <-- call will be considered as side effect free
此類註解會被視為 有效,如果它緊接在函式宣告或常數變數宣告之前,其中第一個宣告的變數是函式,且僅以空白或註解與宣告分隔。
無效註解會被移除,而 Rollup 會發出警告。有效註解會保留在程式碼中,除非其宣告也已移除。
treeshake.correctVarValueBeforeDeclaration
類型 | 布林值 |
---|---|
CLI | --treeshake.correctVarValueBeforeDeclaration /--no-treeshake.correctVarValueBeforeDeclaration |
預設 | false |
在某些特殊情況下,如果變數在宣告指派之前存取,且未重新指派,則 Rollup 可能會錯誤地假設該變數在整個程式中都是常數,如下面的範例所示。不過,如果變數是用 var
宣告的,則不適用,因為這些變數可以在宣告之前存取,而會評估為 undefined
。選擇 true
將可確保 Rollup 對於用 var
宣告的變數值不作任何假設。不過請注意,這可能會對 tree-shaking 結果產生顯著的負面影響。
// everything will be tree-shaken unless treeshake.correctVarValueBeforeDeclaration === true
let logBeforeDeclaration = false;
function logIfEnabled() {
if (logBeforeDeclaration) {
log();
}
var value = true;
function log() {
if (!value) {
console.log('should be retained, value is undefined');
}
}
}
logIfEnabled(); // could be removed
logBeforeDeclaration = true;
logIfEnabled(); // needs to be retained as it displays a log
treeshake.manualPureFunctions
類型 | 字串陣列 |
---|---|
CLI | --treeshake.manualPureFunctions <名稱> |
允許手動定義函式名稱清單,這些函式名稱應始終被視為「純粹」,亦即在呼叫時不會產生副作用,例如變更全域狀態等。檢查僅依據名稱執行。
這不僅有助於移除無用程式碼,還能改善 JavaScript 區塊產生,特別是在使用 output.experimentalMinChunkSize
時。
除了任何符合該名稱的函式之外,純粹函式上的任何屬性,以及從純粹函式傳回的任何函式,也會被視為純粹函式,且存取任何屬性時不會檢查是否有副作用。
// rollup.config.js
export default {
treeshake: {
preset: 'smallest',
manualPureFunctions: ['styled', 'local']
}
// ...
};
// code
import styled from 'styled-components';
const local = console.log;
local(); // removed
styled.div`
color: blue;
`; // removed
styled?.div(); // removed
styled()(); // removed
styled().div(); // removed
treeshake.moduleSideEffects
類型 | 布林值 | 「no-external」 | 字串陣列 | (id: 字串, external: 布林值) => 布林值 |
---|---|
CLI | --treeshake.moduleSideEffects /--no-treeshake.moduleSideEffects /--treeshake.moduleSideEffects no-external |
預設 | true |
如果為 false
,假設模組和外部相依項(未從中匯入任何項目)沒有其他副作用,例如變異全域變數或未檢查就記錄。對於外部相依項,這將會抑制空匯入
// input file
import { unused } from 'external-a';
import 'external-b';
console.log(42);
// output with treeshake.moduleSideEffects === true
import 'external-a';
import 'external-b';
console.log(42);
// output with treeshake.moduleSideEffects === false
console.log(42);
對於非外部模組,false
將不會包含來自模組的任何陳述,除非包含此模組中至少一項匯入
// input file a.js
import { unused } from './b.js';
console.log(42);
// input file b.js
console.log('side-effect');
const ignored = 'will still be removed';
// output with treeshake.moduleSideEffects === true
console.log('side-effect');
console.log(42);
// output with treeshake.moduleSideEffects === false
console.log(42);
您也可以提供具有副作用的模組清單,或提供函式來個別判斷每個模組。值 "no-external"
僅會在可能的情況下移除外部匯入,且等同於函式 (id, external) => !external
;
如果將此旗標設定為 false
的模組從另一個模組重新匯出變數,且使用此變數,則是否掃描重新匯出的模組以找出副作用,取決於重新匯出變數的方式
// input file a.js
import { foo } from './b.js';
console.log(foo);
// input file b.js
// direct reexports will ignore side effects
export { foo } from './c.js';
console.log('this side-effect is ignored');
// input file c.js
// indirect reexports will include side effects
import { foo } from './d.js';
foo.mutated = true;
console.log('this side-effect and the mutation are retained');
export { foo };
// input file d.js
export const foo = 42;
// output with treeshake.moduleSideEffects === false
const foo = 42;
foo.mutated = true;
console.log('this side-effect and the mutation are retained');
console.log(foo);
請注意,儘管名稱如此,此選項並不會「新增」副作用到沒有副作用的模組。如果某個空模組對您來說很重要,因為您需要它進行相依項追蹤,外掛程式介面允許您透過 resolveId
、load
或 transform
掛鉤將模組指定為排除在 tree-shaking 之外。
treeshake.preset
類型 | "smallest" | "safest"| "recommended" |
---|---|
CLI | --treeshake <value> |
允許選擇上面列出的其中一個預設值,同時覆寫一些選項。
export default {
treeshake: {
preset: 'smallest',
propertyReadSideEffects: true
}
// ...
};
treeshake.propertyReadSideEffects
類型 | 布林值| 'always' |
---|---|
CLI | --treeshake.propertyReadSideEffects /--no-treeshake.propertyReadSideEffects |
預設 | true |
如果為 true
,保留 Rollup 可判斷具有副作用的未使用的屬性讀取。這包括存取 null
或 undefined
的屬性,或透過屬性存取觸發明確的 getter。請注意,這不涵蓋解構指定或傳遞為函式參數的物件上的 getter。
如果為 false
,假設讀取物件的屬性永遠不會有副作用。根據您的程式碼,停用此選項可以大幅縮小套件大小,但如果您依賴於 getter 或非法屬性存取的錯誤,可能會損壞功能。
如果為 'always'
,假設所有成員屬性存取,包括解構,都有副作用。建議將此設定用於依賴於有副作用的 getter 的程式碼。它通常會導致較大的套件大小,但比完全停用 treeshake
小。
// Will be removed if treeshake.propertyReadSideEffects === false
const foo = {
get bar() {
console.log('effect');
return 'bar';
}
};
const result = foo.bar;
const illegalAccess = foo.quux.tooDeep;
treeshake.tryCatchDeoptimization
類型 | 布林值 |
---|---|
CLI | --treeshake.tryCatchDeoptimization /--no-treeshake.tryCatchDeoptimization |
預設 | true |
預設情況下,Rollup 假設在搖樹和不擲出意外錯誤時,執行階段的許多內建全域變數會根據最新規格執行。為了支援依賴於擲出這些錯誤的功能偵測工作流程,Rollup 預設會停用 try 陳述式內的搖樹。如果函式參數從 try 陳述式內部呼叫,也會對此參數進行反最佳化。如果您不需要此功能,並且希望在 try 陳述式內進行搖樹,請將 treeshake.tryCatchDeoptimization
設為 false
。
function otherFn() {
// even though this function is called from a try-statement, the next line
// will be removed as side-effect-free
Object.create(null);
}
function test(callback) {
try {
// calls to otherwise side-effect-free global functions are
// retained inside try-statements for tryCatchDeoptimization: true
Object.create(null);
// calls to other function are retained as well but the body of
// this function may again be subject to tree-shaking
otherFn();
// if a parameter is called, then all arguments passed to that
// function parameter will be deoptimized
callback();
} catch {}
}
test(() => {
// will be ratained
Object.create(null);
});
// call will be retained but again, otherFn is not deoptimized
test(otherFn);
treeshake.unknownGlobalSideEffects
類型 | 布林值 |
---|---|
CLI | --treeshake.unknownGlobalSideEffects /--no-treeshake.unknownGlobalSideEffects |
預設 | true |
由於存取不存在的非內建全域變數會擲出錯誤,因此 Rollup 預設會保留對非內建全域變數的任何存取。將此選項設為 false
以避免此檢查。這對於大多數程式碼庫來說可能是安全的。
// input
const jQuery = $;
const requestTimeout = setTimeout;
const element = angular.element;
// output with unknownGlobalSideEffects == true
const jQuery = $;
const element = angular.element;
// output with unknownGlobalSideEffects == false
const element = angular.element;
在範例中,最後一行始終保留,因為如果 angular
為 null
,存取 element
屬性也可能會擲出錯誤。若要避免此檢查,請將 treeshake.propertyReadSideEffects
也設為 false
。
實驗選項
這些選項反映尚未完全定稿的新功能。因此,可用性、行為和使用方式可能會在次要版本之間有所變更。
experimentalCacheExpiry
類型 | 數字 |
---|---|
CLI | --experimentalCacheExpiry <numberOfRuns> |
預設 | 10 |
決定在多少次執行後,應移除不再由外掛程式使用的快取資產。
experimentalLogSideEffects
類型 | 布林值 |
---|---|
CLI | --experimentalLogSideEffects /--no-experimentalLogSideEffects |
預設 | false |
設為 true
時,這會將在每個檔案中找到的第一個副作用記錄到主控台。這對於找出哪些檔案有副作用以及實際副作用是什麼,會很有幫助。移除副作用可以改善樹狀搖晃和區塊產生,對於讓 output.experimentalMinChunkSize
發揮作用至關重要。
不過,此選項只會記錄頂層陳述。有時,例如在立即呼叫函式表達式的情況下,實際副作用可能會隱藏在巢狀表達式中。
output.experimentalMinChunkSize
類型 | 數字 |
---|---|
CLI | --experimentalMinChunkSize <size> |
預設 | 1 |
為程式碼分割設定設定最小區塊大小目標(以位元組為單位)。當此值設為預設值 1
時,Rollup 會嘗試將不包含程式碼(僅包含匯入和重新匯出)的區塊合併到其他區塊中。只有在不變更任何項目載入時執行的副作用時,才會執行合併。對於值 1
,只允許合併不會增加任何項目載入的程式碼量。
較大的值會嘗試將低於限制的任何區塊合併到其他區塊中。在這種情況下,可以接受項目可能會載入一些不必要的程式碼。不過,演算法總是會嘗試以最小化不必要程式碼的方式進行合併。
很遺憾,由於分塊運作的方式,分塊大小是在任何分塊渲染外掛程式(例如縮小程式)執行之前測量的,這表示您應該使用足夠高的限制來考量這一點。在計算大小時,它會考量頂層陳述式的樹狀搖晃。
perf
類型 | 布林值 |
---|---|
CLI | --perf /--no-perf |
預設 | false |
是否收集效能計時。當從命令列或組態檔使用時,將會顯示關於目前綑綁程序的詳細測量資料。當從 JavaScript API 使用時,傳回的綑綁物件將包含一個額外的 getTimings()
函式,可隨時呼叫以擷取所有累積的測量資料。
getTimings()
傳回下列格式的物件
{
"# BUILD": [ 698.020877, 33979632, 45328080 ],
"## parse modules": [ 537.509342, 16295024, 27660296 ],
"load modules": [ 33.253778999999994, 2277104, 38204152 ],
...
}
對於每個金鑰,第一個數字代表經過時間,第二個數字代表記憶體使用量的變化,第三個數字代表此步驟後的總記憶體使用量。這些步驟的順序是 Object.keys
使用的順序。頂層金鑰以 #
開頭,並包含巢狀步驟的計時,例如在上述範例中,# BUILD
步驟的 698 毫秒包含 ## parse modules
步驟的 538 毫秒。
watch
類型 | WatcherOptions | false |
---|---|
預設 | {} |
interface WatcherOptions {
buildDelay?: number;
chokidar?: ChokidarOptions;
clearScreen?: boolean;
exclude?: string | RegExp | (string | RegExp)[];
include?: string | RegExp | (string | RegExp)[];
skipWrite?: boolean;
}
指定監控模式的選項或防止此組態受到監控。只有在使用組態陣列時,指定 false
才真正有用。在這種情況下,此組態在監控模式變更時不會建置或重建,但它會在定期執行 Rollup 時建置
// rollup.config.js
export default [
{
input: 'main.js',
output: { file: 'bundle.cjs.js', format: 'cjs' }
},
{
input: 'main.js',
watch: false,
output: { file: 'bundle.es.js', format: 'es' }
}
];
這些選項僅在使用 --watch
標記執行 Rollup 或使用 rollup.watch
時才會生效。
watch.buildDelay
類型 | 數字 |
---|---|
CLI | --watch.buildDelay <數字> |
預設 | 0 |
設定 Rollup 在觸發重新建置之前等待進一步變更的時間(以毫秒為單位)。預設情況下,Rollup 沒有等待時間,但 chokidar 實例中設定了一個小型防彈跳超時。將此設定為大於 0
的值,表示 Rollup 只有在沒有變更設定的毫秒數時才會觸發重新建置。如果監控多個設定,Rollup 將使用設定最大的建置延遲。
watch.chokidar
類型 | ChokidarOptions |
---|
傳遞給已套件 chokidar 實例的監控選項的選用物件。請參閱 chokidar 文件 以找出有哪些選項可用。
watch.clearScreen
類型 | 布林值 |
---|---|
CLI | --watch.clearScreen /--no-watch.clearScreen |
預設 | true |
觸發重新建置時是否清除螢幕。
watch.exclude
類型 | 字串 | RegExp | (字串 | RegExp)[] |
---|---|
CLI | --watch.exclude <檔案> |
防止檔案被監控
// rollup.config.js
export default {
...,
watch: {
exclude: 'node_modules/**'
}
};
watch.include
類型 | 字串 | RegExp | (字串 | RegExp)[] |
---|---|
CLI | --watch.include <檔案> |
將檔案監控限制在特定檔案。請注意,這只會過濾模組圖,但不允許新增其他監控檔案
// rollup.config.js
export default {
...,
watch: {
include: 'src/**'
}
};
watch.skipWrite
類型 | 布林值 |
---|---|
CLI | --watch.skipWrite /--no-watch.skipWrite |
預設 | false |
觸發重新建置時是否略過 bundle.write()
步驟。
已棄用的選項
☢️ 這些選項已棄用,並可能在未來的 Rollup 版本中移除。
output.externalImportAssertions
請改用 output.externalImportAttributes
選項。
類型 | 布林值 |
---|---|
CLI | --externalImportAssertions /--no-externalImportAssertions |
預設 | true |
如果輸出格式為 es
,是否在輸出中對外部匯入新增匯入斷言。預設情況下,斷言會從輸入檔案取得,但外掛程式稍後可以新增或移除斷言。例如,import "foo" assert {type: "json"}
將導致相同的匯入出現在輸出中,除非選項設定為 false
。請注意,模組的所有匯入都需要有相符的斷言,否則會發出警告。