-
Notifications
You must be signed in to change notification settings - Fork 2
/
mdx.js
61 lines (57 loc) · 1.52 KB
/
mdx.js
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
57
58
59
60
61
import { name as isIdentifierName } from 'estree-util-is-identifier-name'
import { valueToEstree } from 'estree-util-value-to-estree'
export default function remarkMdxReadingTime({
/**
* The attribute name to export the stored the reading time under data.
*
* @type {string}
* @default "readingTime"
*/
name = 'readingTime',
/**
* The attribute name to store the reading time under data in remark plugin.
*
* @type {string}
* @default "readingTime"
*/
remarkReadingTimeName = 'readingTime'
} = {}) {
if (!isIdentifierName(name)) {
throw new Error(
`The name should be a valid identifier name, got: ${JSON.stringify(
name,
)}`,
)
}
return function transformer(tree, vfile) {
const readingTime = vfile.data[remarkReadingTimeName];
if (readingTime === undefined) return
tree.children.unshift({
type: 'mdxjsEsm',
data: {
estree: {
type: 'Program',
sourceType: 'module',
body: [
{
type: 'ExportNamedDeclaration',
source: null,
specifiers: [],
declaration: {
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: { type: 'Identifier', name },
init: valueToEstree(readingTime),
},
],
},
},
],
},
},
})
}
}