@web/rollup-plugin-html
Version:
Rollup plugin for bundling HTML files
63 lines • 3.43 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.injectedUpdatedAssetPaths = void 0;
const parse5_utils_1 = require("@web/parse5-utils");
const path_1 = __importDefault(require("path"));
const utils_js_1 = require("../assets/utils.js");
const utils_js_2 = require("../utils.js");
const utils_js_3 = require("./utils.js");
function getSrcSetUrlWidthPairs(srcset) {
if (!srcset) {
return [];
}
const srcsetParts = srcset.includes(',') ? srcset.split(',') : [srcset];
const urls = srcsetParts
.map(url => url.trim())
.map(url => (url.includes(' ') ? url.split(' ') : [url]));
return urls;
}
function injectedUpdatedAssetPaths(args) {
const { document, input, outputDir, rootDir, emittedAssets, externalAssets, publicPath = './', absolutePathPrefix, } = args;
const assetNodes = (0, utils_js_1.findAssets)(document);
const isExternal = (0, utils_js_1.createAssetPicomatchMatcher)(externalAssets);
for (const node of assetNodes) {
const sourcePaths = (0, utils_js_1.getSourcePaths)(node);
for (const sourcePath of sourcePaths) {
if (isExternal(sourcePath))
continue;
const htmlFilePath = input.filePath ? input.filePath : path_1.default.join(rootDir, input.name);
const htmlDir = path_1.default.dirname(htmlFilePath);
const filePath = (0, utils_js_1.resolveAssetFilePath)(sourcePath, htmlDir, rootDir, absolutePathPrefix);
const assetPaths = (0, utils_js_1.isHashedAsset)(node) ? emittedAssets.hashed : emittedAssets.static;
const relativeOutputPath = assetPaths.get(filePath);
if (!relativeOutputPath) {
throw (0, utils_js_2.createError)(`Something went wrong while bundling HTML file ${input.name}. Could not find ${filePath} in emitted rollup assets.`);
}
const htmlOutputFilePath = path_1.default.join(outputDir, input.name);
const htmlOutputDir = path_1.default.dirname(htmlOutputFilePath);
const absoluteOutputPath = path_1.default.join(outputDir, relativeOutputPath);
const relativePathToHtmlFile = path_1.default.relative(htmlOutputDir, absoluteOutputPath);
const browserPath = path_1.default.posix.join(publicPath, (0, utils_js_3.toBrowserPath)(relativePathToHtmlFile));
const key = (0, utils_js_1.getSourceAttribute)(node);
let newAttributeValue = browserPath;
if (key === 'srcset') {
const srcset = (0, parse5_utils_1.getAttribute)(node, key);
if (srcset) {
const urlWidthPairs = getSrcSetUrlWidthPairs(srcset);
for (const urlWidthPair of urlWidthPairs) {
if (urlWidthPair[0] === sourcePath) {
urlWidthPair[0] = browserPath;
}
}
newAttributeValue = urlWidthPairs.map(urlWidthPair => urlWidthPair.join(' ')).join(', ');
}
}
(0, parse5_utils_1.setAttribute)(node, key, newAttributeValue);
}
}
}
exports.injectedUpdatedAssetPaths = injectedUpdatedAssetPaths;
//# sourceMappingURL=injectedUpdatedAssetPaths.js.map