Skip to content

Commit

Permalink
main: fix url rewriter
Browse files Browse the repository at this point in the history
  • Loading branch information
SomeHats committed Feb 18, 2024
1 parent cbb5737 commit 67faab5
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,40 @@ function resolveATags(): PluginOption {
return {
name: "resolve-a-tags",
transformIndexHtml: (html, ctx) => {
return html.replace(
/(<a [^>]*?href=")([^"]+?)("[^>]*?>)/g,
(_, pre, url, post) => {
return `${pre}${path.join(baseUrl, url)}${post}`;
},
);
for (let i = 0; i < html.length; i++) {
if (
html[i] !== "<" ||
html[i + 1] !== "a" ||
!html[i + 2].match(/\s/)
) {
continue;
}

const tagStart = i;
let tagEnd = null;
for (; i < html.length; i++) {
if (html[i] !== ">") continue;
tagEnd = i;
break;
}
if (tagEnd === null) continue;

const tag = html.slice(tagStart, tagEnd + 1);
if (!tag.includes("href")) continue;
const hrefStart = tag.indexOf('href="') + 'href="'.length;
const hrefEnd = tag.indexOf('"', hrefStart);
const href = tag.slice(hrefStart, hrefEnd);
const newHref = path.join(baseUrl, href);

html =
html.slice(0, tagStart + hrefStart) +
newHref +
html.slice(tagStart + hrefEnd);

i = tagEnd;
}

return html;
},
};
}
Expand Down

0 comments on commit 67faab5

Please sign in to comment.