Namer
命名外掛決定了套件的輸出檔名。命名器會在管線中執行,直到其中一個回傳結果。回傳的檔案路徑應該相對於目標 distDir
。有關此項目的詳細資訊,請參閱 目標。
覆寫特定套件的名稱
#命名器外掛的常見用途是覆寫 Parcel 的特定套件的預設命名方式。當命名器無法處理套件時,可能會回傳 null
,以允許管線中的下一個命名器來處理它。有關此項目的詳細資訊,請參閱 Parcel 組態文件中的 命名器。
此範例將所有 png
和 jpg
檔案放入與其原始檔名相同的 images
資料夾中。
import {Namer} from '@parcel/plugin';
import path from 'path';
export default new Namer({
name({bundle}) {
if (bundle.type === 'png' || bundle.type === 'jpg') {
let filePath = bundle.getMainEntry().filePath;
return `images/${path.basename(filePath)}`;
}
// Allow the next namer to handle this bundle.
return null;
}
});
注意:此範例並未確保所有檔名都是唯一的。如果兩個影像在不同的目錄中具有相同的檔名,則建置會失敗。
內容雜湊
#將套件內容的雜湊包含在內,是生產建置中的一項重要最佳化,可讓瀏覽器無限期快取已載入的檔案。當套件的內容變更時,其檔名也會變更,這會作為快取失效機制。有關此項目的詳細資訊,請參閱 內容雜湊 文件。
在命名包組的階段,最終內容尚未得知,因此 Parcel 在每個 Bundle
物件上提供了 hashReference
屬性。這是一個不透明的佔位符值,稍後在寫入最終包組時會被實際雜湊值取代。在回傳的包組名稱中使用它來包含內容雜湊。
在包含雜湊之前,請務必檢查 bundle.needsStableName
屬性。當此屬性為 true
時,表示某個依賴項預期包組的檔名會隨著時間保持一致。例如,服務工作人員要求其 URL 永遠不會變更,而使用者預期 HTML 頁面等可見 URL 具有可讀性且保持一致。
import {Namer} from '@parcel/plugin';
export default new Namer({
name({bundle}) {
let name = yourNamingFunction(bundle);
if (!bundle.needsStableName) {
name += "." + bundle.hashReference;
}
return name + "." + bundle.type;
}
});
即使在停用內容雜湊(例如在開發階段或使用 --no-content-hash
)的情況下,雜湊也是確保回傳的包組名稱唯一的絕佳方法。在這種情況下,hashReference
會被原始檔案路徑的雜湊值取代,而此雜湊值不會隨著時間而變更。
目標
#命名器外掛程式也應尊重與包組相關聯的 Target
。目標 允許使用者在 package.json
中設定輸入包組的輸出檔名。如果包組位於輸入包組群組中且包含輸入資產,則命名器外掛程式應在可用時使用 bundle.target.distEntry
作為輸出檔名。
import {Namer} from '@parcel/plugin';
export default new Namer({
name({bundle, bundleGraph}) {
let bundleGroup = bundleGraph
.getBundleGroupsContainingBundle(bundle)[0];
let isEntry = bundleGraph.isEntryBundleGroup(bundleGroup);
let bundleGroupBundles = bundleGraph
.getBundlesInBundleGroup(bundleGroup);
let mainBundle = bundleGroupBundles.find(b =>
b.getEntryAssets()
.some(a => a.id === bundleGroup.entryAssetId),
);
if (
isEntry &&
bundle.id === mainBundle.id &&
bundle.target?.distEntry
) {
return bundle.target.distEntry;
}
// ...
}
});
載入設定檔
#應在命名器外掛程式的 loadConfig
方法中從使用者的專案載入設定檔。有關如何執行此操作的詳細資訊,請參閱 載入設定檔。
注意:使用 Parcel 的設定檔載入機制非常重要,才能適當地失效快取。避免直接從檔案系統載入檔案。
相關 API
#Namer parcel/packages/core/types/index.js:1597
type Namer<ConfigType> = {|
loadConfig?: ({|
config: Config,
options: PluginOptions,
logger: PluginLogger,
|}) => Promise<ConfigType> | ConfigType,
name({|
bundle: Bundle,
bundleGraph: BundleGraph<Bundle>,
config: ConfigType,
options: PluginOptions,
logger: PluginLogger,
|}): Async<?FilePath>,
傳回檔案名稱/-路徑給 bundle
或 nullish 以留給下一個 namer 外掛程式。
|}