Home / Function/ rehypeImages() — astro Function Reference

rehypeImages() — astro Function Reference

Architecture documentation for the rehypeImages() function in rehype-images.ts from the astro codebase.

Entity Profile

Dependency Diagram

graph TD
  04ab094e_9cf4_a8db_9600_e91c80bfa78e["rehypeImages()"]
  48b62bf2_8b05_a54d_92ee_3c8a524eed54["rehype-images.ts"]
  04ab094e_9cf4_a8db_9600_e91c80bfa78e -->|defined in| 48b62bf2_8b05_a54d_92ee_3c8a524eed54
  style 04ab094e_9cf4_a8db_9600_e91c80bfa78e fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

packages/markdown/remark/src/rehype-images.ts lines 16–67

export function rehypeImages() {
	return function (tree: Root, file: VFile) {
		if (!file.data.astro?.localImagePaths?.length && !file.data.astro?.remoteImagePaths?.length) {
			// No images to transform, nothing to do.
			return;
		}

		const imageOccurrenceMap = new Map();

		visit(tree, 'element', (node) => {
			if (node.tagName !== 'img') return;
			if (typeof node.properties?.src !== 'string') return;

			const src = decodeURI(node.properties.src);
			let imageProperties: Properties;

			if (file.data.astro?.localImagePaths?.includes(src)) {
				// Override the original `src` with the new, decoded `src` that Astro will better understand.
				imageProperties = { ...node.properties, src };
			} else if (file.data.astro?.remoteImagePaths?.includes(src)) {
				imageProperties = {
					// By default, markdown images won't have width and height set. However, just in case another user plugin does set these, we should respect them.
					inferSize: 'width' in node.properties && 'height' in node.properties ? undefined : true,
					...node.properties,
					src,
				};
			} else {
				// Not in localImagePaths or remoteImagePaths, we should not transform.
				return;
			}

			// Separate HAST-only properties from image processing properties
			const hastProperties: Properties = {};
			for (const key of HAST_PRESERVED_PROPERTIES) {
				if (key in imageProperties) {
					hastProperties[key] = imageProperties[key];
					delete imageProperties[key];
				}
			}

			// Initialize or increment occurrence count for this image
			const index = imageOccurrenceMap.get(node.properties.src) || 0;
			imageOccurrenceMap.set(node.properties.src, index + 1);

			// Set a special property on the image so later Astro code knows to process this image.
			node.properties = {
				...hastProperties,
				__ASTRO_IMAGE_: JSON.stringify({ ...imageProperties, index }),
			};
		});
	};
}

Domain

Subdomains

Frequently Asked Questions

What does rehypeImages() do?
rehypeImages() is a function in the astro codebase, defined in packages/markdown/remark/src/rehype-images.ts.
Where is rehypeImages() defined?
rehypeImages() is defined in packages/markdown/remark/src/rehype-images.ts at line 16.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free