-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
182 lines (155 loc) · 6.15 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
const frontmatter = require('front-matter')
const Mode = require('./mode')
const markdownIt = require('markdown-it');
const stringify = (src) => JSON.stringify(src).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
function getNormalizedMarkdownCompiler (options, isReactEnabled) {
if (options.markdown && options.markdownIt) {
throw new Error(
"Both markdown and markdownIt options were specified. This is not supported. \n" +
"Please refer to the documentation for usage: \n" +
"https://hmsk.github.io/frontmatter-markdown-loader/options.html#markdown-compilation"
);
}
// If you've specified the markdown option, hand over control
if (options.markdown) {
return { render: options.markdown };
}
// If you've passed in a MarkdownIt instance, just use that
if (options.markdownIt instanceof markdownIt || (options.markdownIt && options.markdownIt.constructor && options.markdownIt.constructor.name === 'MarkdownIt')) {
return options.markdownIt;
}
// Configuration object? Pass it to our default compiler
if (typeof options.markdownIt === 'object') {
return markdownIt(options.markdownIt);
}
// If no configuration is passed - use a sensible default
return markdownIt(isReactEnabled ? { html: true, xhtmlOut: true } : { html: true });
}
module.exports = function (source) {
if (this.cacheable) this.cacheable();
const options = this.getOptions();
const requestedMode = Array.isArray(options.mode) ? options.mode : [Mode.HTML];
const enabled = (mode) => requestedMode.includes(mode);
let exported = '', prependOutput = '';
const addPrepend = (code) => {
prependOutput = prependOutput.concat(`${code}\n`)
};
const addProperty = (key, value) => {
exported += `
${key}: ${value},
`;
};
const fm = frontmatter(source);
const markdownCompiler = getNormalizedMarkdownCompiler(options, enabled(Mode.REACT));
fm.html = markdownCompiler.render(fm.body);
addProperty('attributes', stringify(fm.attributes));
if (enabled(Mode.HTML)) addProperty('html', stringify(fm.html));
if (enabled(Mode.BODY)) addProperty('body', stringify(fm.body));
if (enabled(Mode.META)) {
const meta = {
resourcePath: this.resourcePath
};
addProperty('meta', stringify(meta));
}
if ((enabled(Mode.VUE_COMPONENT) || enabled(Mode.VUE_RENDER_FUNCTIONS))) {
let vueCompiler, compileVueTemplate;
try {
vueCompiler = require('vue-template-compiler')
compileVueTemplate = require('@vue/component-compiler-utils').compileTemplate
} catch (err) {
if (err.code === "MODULE_NOT_FOUND") {
throw new Error(
"Failed to import vue-template-compiler or/and @vue/component-compiler-utils: \n" +
"If you intend to use 'vue-component', `vue-render-functions` mode, install both to your project: \n" +
"https://hmsk.github.io/frontmatter-markdown-loader/vue.html"
);
} else {
throw err;
}
}
const vueRootClass = options.vue && options.vue.root ? options.vue.root : 'frontmatter-markdown';
const template = fm
.html
.replace(/<(code\s[^>]+)>/g, "<$1 v-pre>")
.replace(/<code>/g, "<code v-pre>");
const compileOptions = {
source: `<div class="${vueRootClass}">${template}</div>`,
filename: this.resourcePath,
compiler: vueCompiler,
compilerOptions: {
outputSourceRange: true
},
transformAssetUrls: (options.vue && (options.vue.transformAssetUrls === false || options.vue.transformAssetUrls)) ? options.vue.transformAssetUrls : true,
isProduction: process.env.NODE_ENV === 'production'
};
const compiled = compileVueTemplate(compileOptions);
addPrepend(`function extractVueFunctions () {\n${compiled.code}\nreturn { render: render, staticRenderFns: staticRenderFns }\n}\nconst vueFunctions = extractVueFunctions()`);
let vueOutput = '';
if (enabled(Mode.VUE_RENDER_FUNCTIONS)) {
vueOutput += `
render: vueFunctions.render,
staticRenderFns: vueFunctions.staticRenderFns,
`;
}
if (enabled(Mode.VUE_COMPONENT)) {
vueOutput += `
component: {
data: function () {
return {
templateRender: null
}
},
render: function (createElement) {
return this.templateRender ? this.templateRender() : createElement("div", "Rendering");
},
created: function () {
this.templateRender = vueFunctions.render;
this.$options.staticRenderFns = vueFunctions.staticRenderFns;
}
}
`;
}
addProperty('vue', `{${vueOutput}}`);
}
if (enabled(Mode.REACT)) {
let babelCore;
const reactRootClass = options.react && options.react.root ? options.react.root : 'frontmatter-markdown';
try {
babelCore = require('@babel/core');
require('@babel/preset-react');
} catch (err) {
throw new Error(
"Failed to import @babel/core or/and @babel/preset-react: \n" +
"If you intend to use 'react' mode, install both to your project: \n" +
"https://hmsk.github.io/frontmatter-markdown-loader/react.html"
);
}
addPrepend(`const React = require('react')`);
const escape = (str) => str.replace(/([\\`])/g, "\\$1");
const template = fm
.html
.replace(/<code(\s[^>]+)>(.+?)<\/code>/sg, (match, p1, p2) => `<code${p1} dangerouslySetInnerHTML={{ __html: \`${escape(p2)}\`}} />`)
.replace(/<code>(.+?)<\/code>/sg, (match, p1) => `<code dangerouslySetInnerHTML={{ __html: \`${escape(p1)}\`}} />`)
.replace(/<(code|pre)([^\s>]*)\sclass=([^>]+)>/g, "<$1$2 className=$3>")
const compiled = babelCore
.transformSync(`
const markdown =
<div className="${reactRootClass}">
${template}
</div>
`, {
presets: ['@babel/preset-react']
});
const reactComponent = `
function (props) {
Object.keys(props).forEach(function (key) {
this[key] = props[key]
})
${compiled.code}
return markdown
}
`
addProperty('react', reactComponent);
}
return `${prependOutput}\nmodule.exports = { ${exported} }`;
}