UNPKG

vite-preload-images-plugin

Version:

A Vite plugin that automatically generates preload tags for images in your build output

124 lines (123 loc) 4.54 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { default: () => preloadImagesPlugin }); module.exports = __toCommonJS(index_exports); var import_fs = __toESM(require("fs")); var import_path = __toESM(require("path")); var import_fast_glob = __toESM(require("fast-glob")); function preloadImagesPlugin(options = {}) { const { preloadDirs = ["src/assets"], lowPriorityDirs = ["gif"], excludeFiles = [], imageExtensions = ["png", "jpg", "jpeg", "gif", "webp"], debug = false } = options; return { name: "vite-preload-images-plugin", apply: "build", // 只在生产构建时应用 async transformIndexHtml(html, ctx) { if (ctx.bundle) { const preloadTags = generatePreloadTags(html, ctx.bundle, { preloadDirs, lowPriorityDirs, excludeFiles, imageExtensions, debug }); if (debug) { console.log("Generated preload tags:", preloadTags); } if (preloadTags) { return html.replace( "</head>", ` <!-- Auto-generated preload tags --> ${preloadTags} </head>` ); } } return html; } }; } function generatePreloadTags(html, bundle, options) { const { preloadDirs, lowPriorityDirs, excludeFiles, imageExtensions, debug } = options; const imageFiles = preloadDirs.flatMap((dir) => { if (debug) { console.log(`Searching for images in: ${dir}`); } if (!import_fs.default.existsSync(dir)) { if (debug) { console.log(`Directory does not exist: ${dir}`); } return []; } return import_fast_glob.default.sync(`${dir}/**/*.{${imageExtensions.join(",")}}`, { onlyFiles: true, absolute: true, ignore: excludeFiles.map((file) => `**/${file}`) }); }); if (debug) { console.log(`Found ${imageFiles.length} image files`); } const preloadTags = imageFiles.map((file) => { const relativePath = import_path.default.relative(import_path.default.resolve(process.cwd(), "src"), file); const assetPath = findAssetPath(relativePath, bundle); if (!assetPath) { if (debug) { console.log(`Could not find asset path for: ${relativePath}`); } return null; } const dirName = import_path.default.dirname(relativePath).split(import_path.default.sep)[0]; const fetchPriority = lowPriorityDirs.includes(dirName) ? ' fetchpriority="low"' : ""; return `<link rel="preload" as="image" href="${assetPath}"${fetchPriority}>`; }).filter(Boolean).join("\n "); return preloadTags; } function findAssetPath(relativePath, bundle) { const normalizedPath = relativePath.replace(/\\/g, "/").replace(/^assets\//, ""); for (const [fileName, chunkInfo] of Object.entries(bundle)) { if (fileName.startsWith("assets/") && chunkInfo.type === "asset" && chunkInfo.name) { const baseName = chunkInfo.name.replace(/\.[a-f0-9]{8}\./, ".").replace(/%20/g, " "); if (normalizedPath.includes(baseName)) { return `./${fileName}`; } } } return null; } //# sourceMappingURL=index.js.map