HTML Loader provides runtime helper functions and utilities used during the webpack build process and in the generated module code.
Runtime helper function for processing URLs with optional quote handling.
/**
* Runtime helper for URL processing and quote handling
* Used internally by html-loader for generated module code
* @param url - The URL string to process
* @param maybeNeedQuotes - Whether quotes might be needed around the URL
* @returns Processed URL string, optionally wrapped in quotes if needed
*/
function getUrl(url: string, maybeNeedQuotes?: boolean): string;Usage Context:
This function is automatically injected by html-loader when processing HTML attributes that require runtime URL handling. It's not typically called directly by user code.
Internal Behavior:
// The getUrl function handles several cases:
// 1. Null/undefined URLs
getUrl(null) // returns null
getUrl(undefined) // returns undefined
// 2. URL quote wrapping when needed
getUrl("path/to/file.jpg", true) // may return "path/to/file.jpg" with quotes
getUrl("simple-path", false) // returns simple-path without quotes
// 3. Special character handling
getUrl("path with spaces.jpg", true) // returns "path with spaces.jpg"
getUrl("path<with>special.jpg", true) // returns "path<with>special.jpg"Generated Code Example:
When html-loader processes HTML with assets, it generates code that uses the getUrl helper:
// Original HTML
// <img src="./image.png" alt="example">
// Generated module code (simplified)
import ___HTML_LOADER_GET_SOURCE_FROM_IMPORT___ from "html-loader/dist/runtime/getUrl.js";
import img from "./image.png";
var code = `<img src="${___HTML_LOADER_GET_SOURCE_FROM_IMPORT___(img, true)}" alt="example">`;
export default code;Internal utilities for generating JavaScript module code from HTML content.
/**
* Generate import statements for assets referenced in HTML
* @param html - Processed HTML content
* @param imports - Array of import objects
* @param options - Generation options
* @returns Generated import code string
*/
function getImportCode(html: string, imports: ImportItem[], options: GenerationOptions): string;
/**
* Generate main module code with asset replacements
* @param html - HTML content with replacement placeholders
* @param replacements - Array of replacement objects
* @param loaderContext - Webpack loader context
* @param options - Generation options
* @returns Generated module code string
*/
function getModuleCode(
html: string,
replacements: ReplacementItem[],
loaderContext: LoaderContext,
options: GenerationOptions
): string;
/**
* Generate export statement for the module
* @param html - Final HTML content
* @param options - Generation options including module format
* @returns Generated export code string
*/
function getExportCode(html: string, options: GenerationOptions): string;
interface ImportItem {
importName: string;
request: string;
}
interface ReplacementItem {
importName: string;
replacementName: string;
isValueQuoted: boolean;
hash?: string;
}
interface GenerationOptions {
esModule: boolean;
isTemplateLiteralSupported?: boolean;
}Generated Code Examples:
// ES Module format (esModule: true)
import img1 from "./image1.png";
import img2 from "./image2.png";
var code = `<img src="${img1}" alt="first"><img src="${img2}" alt="second">`;
export default code;
// CommonJS format (esModule: false)
var img1 = require("./image1.png");
var img2 = require("./image2.png");
var code = "<img src=\"" + img1 + "\" alt=\"first\"><img src=\"" + img2 + "\" alt=\"second\">";
module.exports = code;
// With URL helper (when quotes are needed)
import ___HTML_LOADER_GET_SOURCE_FROM_IMPORT___ from "html-loader/dist/runtime/getUrl.js";
import img from "./image with spaces.png";
var code = `<img src="${___HTML_LOADER_GET_SOURCE_FROM_IMPORT___(img, true)}">`;
export default code;Utilities for detecting and generating template literal syntax.
/**
* Check if template literals are supported in the current webpack environment
* @param loaderContext - Webpack loader context
* @returns true if template literals can be used in generated code
*/
function supportTemplateLiteral(loaderContext: LoaderContext): boolean;
/**
* Convert a string to template literal format with proper escaping
* @param str - String to convert
* @returns Template literal string with escaped special characters
*/
function convertToTemplateLiteral(str: string): string;Usage Examples:
// Template literal detection
const useTemplateLiterals = supportTemplateLiteral(loaderContext);
if (useTemplateLiterals) {
// Generate: `<img src="${img}">`
code = convertToTemplateLiteral(htmlContent);
} else {
// Generate: "<img src=\"" + img + "\">"
code = JSON.stringify(htmlContent);
}
// Template literal escaping
convertToTemplateLiteral("Hello `world` ${}")
// Returns: `Hello \`world\` \${}`
convertToTemplateLiteral("Line 1\nLine 2")
// Returns: `Line 1\nLine 2`Utilities for validating and processing URLs for webpack compatibility.
/**
* Check if a URL should be processed as a webpack request
* @param url - URL to validate
* @param options - Validation options
* @returns true if URL should be processed by webpack
*/
function isURLRequestable(url: string, options: {
isSupportDataURL?: boolean;
isSupportAbsoluteURL?: boolean;
}): boolean;
/**
* Convert URLs to webpack request format
* @param context - Webpack context directory
* @param request - URL to convert
* @returns Webpack-compatible request string
*/
function requestify(context: string, request: string): string;URL Processing Examples:
// URL validation
isURLRequestable("./image.png") // true - relative path
isURLRequestable("/absolute/path.png") // true - root relative
isURLRequestable("https://example.com/img.png") // false - external URL
isURLRequestable("data:image/png;base64,...", { isSupportDataURL: true }) // true - data URL
// Request conversion
requestify("/project/src", "./image.png") // "./image.png"
requestify("/project", "/absolute/image.png") // "../absolute/image.png"
requestify("/project", "C:\\Windows\\image.png") // "./image.png" (Windows)Utilities for parsing HTML attributes and content.
/**
* Parse HTML src attribute values
* @param input - Src attribute value
* @returns Parsed source object with value and offset information
*/
function parseSrc(input: string): SourceParsed;
/**
* Parse HTML srcset attribute values
* @param input - Srcset attribute value
* @returns Array of parsed source objects with descriptors
*/
function parseSrcset(input: string): SourceSetParsed[];
interface SourceParsed {
value: string;
startOffset: number;
}
interface SourceSetParsed {
source: SourceParsed;
width?: { value: number };
density?: { value: number };
height?: { value: number };
}Parsing Examples:
// Src parsing
parseSrc(" ./image.png ")
// Returns: { value: "./image.png", startOffset: 2 }
// Srcset parsing
parseSrcset("image-1x.png 1x, image-2x.png 2x, image-large.png 1200w")
// Returns: [
// { source: { value: "image-1x.png", startOffset: 0 }, density: { value: 1 } },
// { source: { value: "image-2x.png", startOffset: 15 }, density: { value: 2 } },
// { source: { value: "image-large.png", startOffset: 30 }, width: { value: 1200 } }
// ]Custom error class for HTML processing errors with source position information.
/**
* Custom error class for HTML source errors with position information
*/
class HtmlSourceError extends Error {
/**
* Create an HTML source error with position context
* @param error - Error message
* @param startOffset - Character offset where error starts
* @param endOffset - Character offset where error ends
* @param source - Complete HTML source content
*/
constructor(error: string, startOffset: number, endOffset: number, source: string);
/** Error name identifier */
name: "HtmlSourceError";
/** Starting character position of the error */
startOffset: number;
/** Ending character position of the error */
endOffset: number;
/** Complete HTML source content */
source: string;
}Error Example:
// HTML with error
const html = `<img src="broken-url">`;
// Create contextual error
const error = new HtmlSourceError(
"Invalid URL format",
10, // start of "broken-url"
20, // end of "broken-url"
html
);
console.log(error.message);
// "HtmlSourceError: Invalid URL format (From line 1, column 11; to line 1, column 21)"Utilities for the html-loader plugin system.
/**
* Plugin runner for processing HTML through a pipeline of plugins
* @param plugins - Array of plugin functions
* @returns Object with process method for running the pipeline
*/
function pluginRunner(plugins: PluginFunction[]): {
process(content: string): Promise<{ html: string }>;
};
/**
* Plugin function signature
* @param content - HTML content to process
* @param result - Shared result object between plugins
* @returns Modified HTML content
*/
type PluginFunction = (content: string, result: any) => string | Promise<string>;Plugin Usage:
// Create plugin pipeline
const runner = pluginRunner([
sourcesPlugin(sourcesOptions),
minimizerPlugin(minimizerOptions)
]);
// Process HTML
const { html } = await runner.process(htmlContent);These utilities are primarily used internally by html-loader but understanding them helps when debugging generated code or creating custom integrations.