async function toImageRequireNode()

in packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts [39:84]


async function toImageRequireNode(
  node: Image,
  imagePath: string,
  filePath: string,
) {
  const jsxNode = node as Literal & Partial<Image>;
  let relativeImagePath = posixPath(
    path.relative(path.dirname(filePath), imagePath),
  );
  relativeImagePath = `./${relativeImagePath}`;

  const parsedUrl = url.parse(node.url);
  const hash = parsedUrl.hash ?? '';
  const search = parsedUrl.search ?? '';

  const alt = node.alt ? `alt={"${escapeHtml(node.alt)}"} ` : '';
  const src = `require("${inlineMarkdownImageFileLoader}${
    escapePath(relativeImagePath) + search
  }").default${hash ? ` + '${hash}'` : ''}`;
  const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';
  let width = '';
  let height = '';
  try {
    const size = (await promisify(sizeOf)(imagePath))!;
    if (size.width) {
      width = ` width="${size.width}"`;
    }
    if (size.height) {
      height = ` height="${size.height}"`;
    }
  } catch (err) {
    // Workaround for https://github.com/yarnpkg/berry/pull/3889#issuecomment-1034469784
    // TODO remove this check once fixed in Yarn PnP
    if (!process.versions.pnp) {
      logger.warn`The image at path=${imagePath} can't be read correctly. Please ensure it's a valid image.
${(err as Error).message}`;
    }
  }

  Object.keys(jsxNode).forEach(
    (key) => delete jsxNode[key as keyof typeof jsxNode],
  );

  (jsxNode as Literal).type = 'jsx';
  jsxNode.value = `<img ${alt}src={${src}}${title}${width}${height} />`;
}