1
1
mirror of https://github.com/jxnblk/mdx-deck.git synced 2024-11-30 00:44:20 +03:00
mdx-deck/lib/loader.js

50 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-08-01 01:24:46 +03:00
const { getOptions } = require('loader-utils')
2018-07-28 21:21:36 +03:00
const mdx = require('@mdx-js/mdx')
const matter = require('gray-matter')
2018-07-28 23:46:11 +03:00
const stringifyObject = require('stringify-object')
const normalizeNewline = require('normalize-newline')
2018-07-28 21:21:36 +03:00
2018-07-29 01:36:00 +03:00
const EXREG = /export\sdefault\s\(/g
const MODREG = /^(import|export)\s/
2018-07-31 18:28:14 +03:00
const SLIDEREG = /\n---\n/
2018-07-28 21:21:36 +03:00
module.exports = async function (src) {
const callback = this.async()
2018-08-01 01:24:46 +03:00
const options = getOptions(this) || {}
2018-07-28 21:21:36 +03:00
const { data, content } = matter(src)
const inlineModules = []
const slides = normalizeNewline(content)
.split(SLIDEREG)
2018-08-01 01:24:46 +03:00
.map(str => mdx.sync(str, options))
2018-07-28 21:21:36 +03:00
.map(str => str.trim())
2018-07-29 01:36:00 +03:00
.map(str => str.replace(EXREG, '('))
.map(str => {
2018-07-29 01:32:05 +03:00
const lines = str.split('\n')
inlineModules.push(
...lines.filter(str => MODREG.test(str))
)
return lines.filter(str => !MODREG.test(str))
2018-07-29 01:32:05 +03:00
.filter(Boolean)
.join('\n')
})
2018-07-28 21:21:36 +03:00
const {
2018-07-28 23:46:11 +03:00
modules = []
2018-07-28 21:21:36 +03:00
} = data
const code = `import React from 'react'
import { MDXTag } from '@mdx-js/tag'
2018-07-28 23:46:11 +03:00
${modules.join('\n')}
${inlineModules.join('\n')}
2018-07-28 23:46:11 +03:00
export const meta = ${stringifyObject(data)}
2018-07-28 21:21:36 +03:00
export default [
${slides.join(',\n\n')}
]`
return callback(null, code)
}