-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrelative-md.ts
More file actions
45 lines (39 loc) · 1.04 KB
/
relative-md.ts
File metadata and controls
45 lines (39 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import path from 'path';
import { visit } from 'unist-util-visit';
import type { Plugin } from 'unified';
import type { Root, Link, Image } from 'mdast';
interface Options {
prefix?: string; // 默认 /posts
}
const isRelative = (url: string) => {
return (
!url.startsWith('http://') &&
!url.startsWith('https://') &&
!url.startsWith('/') &&
!url.startsWith('#')
);
};
export const remarkRelativeAssetsToPosts: Plugin<[Options?], Root> = (options = {}) => {
const prefix = options.prefix ?? '/posts';
return tree => {
visit(tree, ['link', 'image'], (node: any) => {
const url = node.url;
if (!isRelative(url)) return;
/**
* Markdown 文件:./ABC.md → /posts/abc
*/
if (url.endsWith('.md')) {
const basename = path.basename(url, '.md');
const slug = basename.toLowerCase();
node.url = `${prefix}/${slug}`;
return;
}
/**
* 图片 / 静态资源:
* ./foo/bar.png → /posts/foo/bar.png
*/
const normalized = url.replace(/^\.\//, '');
node.url = `${prefix}/${normalized}`;
});
};
};