-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathmdx.ts
56 lines (50 loc) · 1.52 KB
/
mdx.ts
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
46
47
48
49
50
51
52
53
54
55
56
/** @format */
import { compile, type CompileOptions } from "https://esm.sh/v126/@mdx-js/mdx@2.3.0";
import type { ModuleLoader, ModuleLoaderEnv, ModuleLoaderOutput, Plugin } from "../server/types.ts";
export class MDXLoader implements ModuleLoader {
#options: CompileOptions;
constructor(options?: CompileOptions) {
this.#options = options ?? {};
}
test(path: string): boolean {
const exts = this.#options?.mdxExtensions ?? ["mdx"];
return exts.some((ext) => path.endsWith(`.${ext}`));
}
async load(
specifier: string,
content: string,
env: ModuleLoaderEnv,
): Promise<ModuleLoaderOutput> {
const ret = await compile(
{ path: specifier, value: content },
{
jsxImportSource: this.#options.jsxImportSource ??
env.jsxConfig?.jsxImportSource,
...this.#options,
providerImportSource: this.#options.providerImportSource
? env.importMap?.imports[
this.#options.providerImportSource
] ?? this.#options.providerImportSource
: undefined,
development: env.isDev,
},
);
return {
code: ret.toString(),
lang: "js",
};
}
}
export default function MdxPlugin(options?: CompileOptions): Plugin {
return {
name: "mdx",
setup(aleph) {
const exts = options?.mdxExtensions ?? ["mdx"];
aleph.loaders = [new MDXLoader(options), ...(aleph.loaders ?? [])];
aleph.router = {
...aleph.router,
exts: [...exts, ...(aleph.router?.exts ?? [])],
};
},
};
}