Skip to content

Commit c50cfd5

Browse files
committed
Allow loading markdown plugins from node_modules
1 parent 2c16c3a commit c50cfd5

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

lib/index.js

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -193,12 +193,7 @@ function renderMarkdown (files, ms, done) {
193193
// render each page
194194
each(pages, (page, fname) => {
195195
const file = files[page.source]
196-
const html = markdownIt({
197-
langPrefix: 'lang-',
198-
highlight: syntaxHighlight,
199-
linkify: true,
200-
html: true
201-
}).render(file.contents.toString())
196+
const html = md(ms.metadata().markdown).render(file.contents.toString())
202197
const $ = cheerio.load(html)
203198

204199
fixHtml($, fname, sources, files, page)
@@ -271,3 +266,40 @@ function inferTitle (contents) {
271266
if (token.type === 'heading') return stripMarkdown(token.text)
272267
}
273268
}
269+
270+
/**
271+
* Private: Returns a markdownIt instance with plugins loaded.
272+
*/
273+
274+
var mdCache = {}
275+
276+
function md (plugins) {
277+
const key = JSON.stringify(plugins || {})
278+
if (mdCache[key]) return mdCache[key]
279+
280+
var md = markdownIt({
281+
langPrefix: 'lang-',
282+
highlight: syntaxHighlight,
283+
linkify: true,
284+
html: true
285+
})
286+
287+
if (plugins) {
288+
Object.keys(plugins).forEach((plugin) => {
289+
const options = plugins[plugin]
290+
let pluginPath =
291+
tryRequire(`markdown-it-${plugin}`) ||
292+
tryRequire(`${process.cwd()}/node_modules/markdown-it-${plugin}`)
293+
if (!pluginPath) throw new Error(`Can't find module 'markdown-it-${plugin}'`)
294+
md = md.use(require(pluginPath), options)
295+
})
296+
}
297+
298+
mdCache[key] = md
299+
return md
300+
}
301+
302+
function tryRequire (name) {
303+
try { return require.resolve(name) } catch (e) {}
304+
}
305+

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"devDependencies": {
2121
"expect": "1.12.0",
2222
"istanbul": "0.3.21",
23+
"markdown-it-decorate": "0.2.0",
2324
"mocha": "2.3.3",
2425
"mocha-clean": "0.4.0",
2526
"mocha-standard": "1.0.0",

0 commit comments

Comments
 (0)