-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathindex.js
95 lines (83 loc) · 2.62 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {getOptions} = require('loader-utils');
const {readFile} = require('fs-extra');
const mdx = require('@mdx-js/mdx');
const emoji = require('remark-emoji');
const matter = require('gray-matter');
const stringifyObject = require('stringify-object');
const slug = require('./remark/slug');
const toc = require('./remark/toc');
const transformImage = require('./remark/transformImage');
const transformLinks = require('./remark/transformLinks');
const DEFAULT_OPTIONS = {
rehypePlugins: [],
remarkPlugins: [emoji, slug, toc],
};
module.exports = async function docusaurusMdxLoader(fileString) {
const callback = this.async();
const {data, content} = matter(fileString);
const reqOptions = getOptions(this) || {};
const options = {
...reqOptions,
remarkPlugins: [
...(reqOptions.beforeDefaultRemarkPlugins || []),
...DEFAULT_OPTIONS.remarkPlugins,
[
transformImage,
{staticDir: reqOptions.staticDir, filePath: this.resourcePath},
],
[
transformLinks,
{staticDir: reqOptions.staticDir, filePath: this.resourcePath},
],
...(reqOptions.remarkPlugins || []),
],
rehypePlugins: [
...(reqOptions.beforeDefaultRehypePlugins || []),
...DEFAULT_OPTIONS.rehypePlugins,
...(reqOptions.rehypePlugins || []),
],
filepath: this.resourcePath,
};
let result;
try {
result = await mdx(content, options);
} catch (err) {
return callback(err);
}
let exportStr = `export const frontMatter = ${stringifyObject(data)};`;
// Read metadata for this MDX and export it.
if (options.metadataPath && typeof options.metadataPath === 'function') {
const metadataPath = options.metadataPath(this.resourcePath);
if (metadataPath) {
// Add as dependency of this loader result so that we can
// recompile if metadata is changed.
this.addDependency(metadataPath);
const metadata = await readFile(metadataPath, 'utf8');
exportStr += `\nexport const metadata = ${metadata};`;
}
}
if (
options.forbidFrontMatter &&
typeof options.forbidFrontMatter === 'function'
) {
if (
options.forbidFrontMatter(this.resourcePath) &&
Object.keys(data).length > 0
) {
return callback(new Error(`Front matter is forbidden in this file`));
}
}
const code = `
import React from 'react';
import { mdx } from '@mdx-js/react';
${exportStr}
${result}
`;
return callback(null, code);
};