Skip to content

Commit

Permalink
feat: add normalize link remark plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
sanyuan0704 committed Sep 24, 2022
1 parent 3f9681d commit a5151f4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 20 deletions.
18 changes: 9 additions & 9 deletions src/node/plugin-island/config.ts
Expand Up @@ -116,15 +116,15 @@ export function pluginConfig(
}
},
configureServer(server) {
return async () => {
// Serve public dir
// Cause by the pre-bundle problem, we have to set the island package as the root dir
// So we need to serve the public dir in user's root dir manually
const publicDir = path.join(config.root, PUBLIC_DIR);
if (await fs.pathExists(publicDir)) {
server.middlewares.use(sirv(publicDir));
}
};
// Serve public dir
// Cause by the pre-bundle problem, we have to set the island package as the root dir
// So we need to serve the public dir in user's root dir manually

const publicDir = path.join(config.root, PUBLIC_DIR);
if (fs.pathExistsSync(publicDir)) {
server.middlewares.use(sirv(publicDir));
}
server.middlewares.use(sirv(config.root));
}
};
}
5 changes: 4 additions & 1 deletion src/node/plugin-mdx/pluginMdxRollup.ts
Expand Up @@ -27,7 +27,10 @@ export async function pluginMdxRollup(
remarkPluginFrontMatter,
[remarkPluginMDXFrontMatter, { name: 'meta' }],
remarkPluginToc,
[remarkPluginNormalizeLink, { base: config.base }]
[
remarkPluginNormalizeLink,
{ base: config.base || '/', enableSpa: config.enableSpa }
]
],
rehypePlugins: [
rehypePluginSlug,
Expand Down
22 changes: 12 additions & 10 deletions src/node/plugin-mdx/remarkPlugins/link.ts
Expand Up @@ -2,34 +2,36 @@ import type { Plugin } from 'unified';
import { visit } from 'unist-util-visit';
import path from 'path';
import { isProduction } from '../../../node/constants';
import { parseUrl } from '../../../node/utils';

/**
* Remark plugin to normalize a link href
*/
export const remarkPluginNormalizeLink: Plugin<[{ base: string }]> =
({ base }) =>
export const remarkPluginNormalizeLink: Plugin<
[{ base: string; enableSpa: boolean }]
> =
({ base, enableSpa }) =>
(tree) => {
visit(
tree,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(node: any) => node.type === 'a',
(node: any) => node.type === 'link',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(node: any) => {
let url: string = node.url;
// eslint-disable-next-line prefer-const
let { url, hash } = parseUrl(node.url);
const extname = path.extname(url);

if (extname === '.md' || extname === '.mdx') {
url = url.replace(extname, '');
}

if (
isProduction() &&
!import.meta.env.ENABLE_SPA &&
extname !== '.html'
) {
if (isProduction() && !enableSpa && extname !== '.html') {
url += '.html';
}

if (hash) {
url += `#${hash}`;
}
node.url = path.join(base, url);
}
);
Expand Down

0 comments on commit a5151f4

Please sign in to comment.