fix: preserve hash in asset link (#5690)

This commit is contained in:
Alexey Pyltsyn 2021-10-12 17:49:01 +03:00 committed by GitHub
parent b40e45943e
commit 67403b3b65
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 4 deletions

View file

@ -23,6 +23,7 @@ import type {Link, Literal} from 'mdast';
const {
loaders: {inlineMarkdownLinkFileLoader},
} = getFileLoaderUtils();
const hashRegex = /#.*$/;
interface PluginOptions {
filePath: string;
@ -56,6 +57,9 @@ function toAssetRequireNode({
let relativeRequireAssetPath = posixPath(
path.relative(path.dirname(filePath), requireAssetPath),
);
const hash = hashRegex.test(node.url)
? node.url.substr(node.url.indexOf('#'))
: '';
// nodejs does not like require("assets/file.pdf")
relativeRequireAssetPath = relativeRequireAssetPath.startsWith('.')
@ -64,9 +68,9 @@ function toAssetRequireNode({
const href = `require('${inlineMarkdownLinkFileLoader}${escapePath(
relativeRequireAssetPath,
)}').default`;
)}').default${hash ? ` + '${hash}'` : ''}`;
const children = stringifyContent(node);
const title = node.title ? `title="${escapeHtml(node.title)}"` : '';
const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';
(node as unknown as Literal).type = 'jsx';
(
@ -82,7 +86,7 @@ async function convertToAssetLinkIfNeeded({
staticDir,
filePath,
}: {node: Link} & PluginOptions) {
const assetPath = node.url;
const assetPath = node.url.replace(hashRegex, '');
const hasSiteAlias = assetPath.startsWith('@site/');
const hasAssetLikeExtension =