mirror of
https://github.com/gkd-kit/docs.git
synced 2024-11-16 04:32:19 +08:00
fix: img src
This commit is contained in:
parent
33ae1240bb
commit
035ff36171
|
@ -1,6 +1,5 @@
|
||||||
import { simple } from 'acorn-walk';
|
import { simple } from 'acorn-walk';
|
||||||
import type { ImportExpression } from 'acorn';
|
import type { ImportExpression } from 'acorn';
|
||||||
import jsdom from 'jsdom';
|
|
||||||
import MagicString from 'magic-string';
|
import MagicString from 'magic-string';
|
||||||
import fs from 'node:fs/promises';
|
import fs from 'node:fs/promises';
|
||||||
import process from 'node:process';
|
import process from 'node:process';
|
||||||
|
@ -72,32 +71,33 @@ export const mirror = (): Plugin | undefined => {
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const Parser = globalThis.DOMParser || new jsdom.JSDOM().window.DOMParser;
|
const Parser =
|
||||||
|
globalThis.DOMParser || new (await import('jsdom')).JSDOM().window.DOMParser;
|
||||||
export const transformHtml = (code: string) => {
|
export const transformHtml = (code: string) => {
|
||||||
if (!useMirror) return;
|
if (!useMirror) return;
|
||||||
if (!code.includes('/assets/')) return;
|
if (!code.includes('/assets/')) return;
|
||||||
// 注意: 如果使用 htmlparser2+dom-serializer, 当 md 文件包含 `<<n` 将出现 Hydration mismatches 错误
|
// 注意: 如果使用 htmlparser2+dom-serializer, 当 md 文件包含 `<<n` 将出现 Hydration mismatches 错误
|
||||||
const doc = new Parser().parseFromString(code, 'text/html');
|
const doc = new Parser().parseFromString(code, 'text/html');
|
||||||
const elements = {
|
Object.entries({
|
||||||
link: 'href',
|
link: 'href',
|
||||||
script: 'src',
|
script: 'src',
|
||||||
};
|
}).forEach(([tag, attr]) => {
|
||||||
Object.entries(elements).forEach(([tag, attr]) => {
|
|
||||||
doc.querySelectorAll(`${tag}[${attr}^="/assets/"]`).forEach((e) => {
|
doc.querySelectorAll(`${tag}[${attr}^="/assets/"]`).forEach((e) => {
|
||||||
e.setAttribute(attr, mirrorBaseUrl + e.getAttribute(attr));
|
e.setAttribute(attr, mirrorBaseUrl + e.getAttribute(attr));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
doc.querySelectorAll('[href^="/"]').forEach((e) => {
|
Object.entries({
|
||||||
const tag = e.tagName.toLowerCase();
|
link: 'href',
|
||||||
const href = e.getAttribute('href');
|
img: 'src',
|
||||||
if (
|
}).forEach(([tag, attr]) => {
|
||||||
(tag === 'img' || tag === 'link') &&
|
doc.querySelectorAll(`${tag}[${attr}^="/"]`).forEach((e) => {
|
||||||
href &&
|
const value = e.getAttribute(attr);
|
||||||
href.lastIndexOf('/') === 0
|
if (value && !value.includes('/', 1)) {
|
||||||
) {
|
e.setAttribute(attr, mirrorBaseUrl + value);
|
||||||
e.setAttribute('href', mirrorBaseUrl + href);
|
}
|
||||||
}
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return doc.documentElement.outerHTML;
|
return doc.documentElement.outerHTML;
|
||||||
};
|
};
|
||||||
|
|
Loading…
Reference in New Issue
Block a user