util.js 1.3 KB
Newer Older
E
Evan You 已提交
1 2 3 4 5 6 7 8 9 10 11 12
exports.normalizeHeadTag = tag => {
  if (typeof tag === 'string') {
    tag = [tag]
  }
  const tagName = tag[0]
  return {
    tagName,
    attributes: tag[1] || {},
    innerHTML: tag[2] || '',
    closeTag: !(tagName === 'meta' || tagName === 'link')
  }
}
E
Evan You 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26

exports.applyUserWebpackConfig = function (userConfig, config, isServer) {
  const merge = require('webpack-merge')
  if (typeof userConfig === 'object') {
    return merge(config, userConfig)
  }
  if (typeof userConfig === 'function') {
    const res = userConfig(config, isServer)
    if (res && typeof res === 'object') {
      return merge(config, res)
    }
  }
  return config
}
E
Evan You 已提交
27 28 29 30 31 32 33 34 35 36

exports.inferTitle = function (frontmatter) {
  if (frontmatter.title) {
    return frontmatter.title
  }
  const match = frontmatter.__content.trim().match(/^#+\s+(.*)/)
  if (match) {
    return match[1]
  }
}
E
Evan You 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

exports.extractHeaders = (file, include = []) => {
  const fs = require('fs')
  const md = require('./markdown')({})
  const S = require('string')
  const content = fs.readFileSync(file, 'utf-8')
  const tokens = md.parse(content)

  const res = []
  tokens.forEach((t, i) => {
    if (t.type === 'heading_open' && include.includes(t.tag)) {
      const title = tokens[i + 1].content
      res.push({
        title,
        slug: S(title).slugify()
      })
    }
  })
  return res
}