-
Notifications
You must be signed in to change notification settings - Fork 0
/
burdocImportsLoader.js
94 lines (79 loc) · 2.28 KB
/
burdocImportsLoader.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
'use strict';
const path = require('path');
const glob = require('glob');
const loaderUtils = require('loader-utils');
const docsImportsPlaceholder = 'BURDOC_DOCS_IMPORTS';
const sectionConfigsPlaceholder = 'BURDOC_SECTION_CONFIGS';
function getDirs(docsPath) {
console.log('> Gathering directories to watch for changes');
return glob.sync('**/', { cwd: docsPath });
}
function getDocsImportsCode(docsPath) {
console.log('> Gathering the docs');
const docs = glob.sync('**/*.docs.js', { cwd: docsPath, nodir: true });
return `
(function getBurdocDocsImports() {
return [
${docs
.map(
doc => `
[
${JSON.stringify(doc)},
dynamic({
loader: () => import(${JSON.stringify(path.resolve(docsPath, doc))}),
}),
],
`,
)
.join('')}
];
}())
`;
}
function getSectionConfigsCode(docsPath) {
console.log('> Gathering the sections');
const sections = glob.sync('**/burdoc.section.js', { cwd: docsPath, nodir: true });
return `
[
${sections
.sort((sectionA, sectionB) => sectionA.length - sectionB.length || sectionA.localeCompare(sectionB))
.map(
section => `
[
${JSON.stringify(section.replace(/burdoc\.section\.js$/, ''))},
require(${JSON.stringify(path.resolve(docsPath, section))}),
],
`,
)
.join('')}
]
`;
}
function getDocsPath(context) {
return loaderUtils.getOptions(context).docsPath;
}
function addContextDependencies(context, docsPath) {
context.addContextDependency(docsPath);
for (const dir of getDirs(docsPath)) {
context.addContextDependency(path.join(docsPath, dir));
}
}
module.exports = function burdocImportsLoader(originalContent) {
let content = originalContent;
if (content.includes(docsImportsPlaceholder)) {
const docsPath = getDocsPath(this);
content = [
"import dynamic from 'next/dynamic';",
content.replace(docsImportsPlaceholder, getDocsImportsCode(docsPath)),
].join('\n');
this.cacheable(false);
addContextDependencies(this, docsPath);
}
if (content.includes(sectionConfigsPlaceholder)) {
const docsPath = getDocsPath(this);
content = content.replace(sectionConfigsPlaceholder, getSectionConfigsCode(docsPath));
this.cacheable(false);
addContextDependencies(this, docsPath);
}
return content;
};