normallizeLink.js 843 字节
Newer Older
D
DCloud_LXH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
const fs = require('fs')
const folderNames = []
fs.readdirSync('docs').forEach(item => {
  fs.lstatSync(`docs/${item}`).isDirectory() && folderNames.push(item)
})

function isExternal(path) {
  return /^[a-z]+:/i.test(path)
}

function normalizeLink(url) {
  if (!url.startsWith('/') && folderNames.some(item => url.split('/')[0] === item)) {
    return '/' + url
  }
  return url
}

module.exports = function (md) {
  md.normalizeLink = (function (oldNormalizeLink) {
    return function (url) {
      url = isExternal(url)
        ? url
        : normalizeLink(url)
D
DCloud_LXH 已提交
24 25 26
          .replace(/\.md\b/, '.html')
          .replace(/\bREADME\b/, 'index.html')
          .replace(/\/index(?!\.)/, 'index.html')
D
DCloud_LXH 已提交
27 28 29 30 31 32
          .replace(/\?id=/, '#')
          .replace(/\\/g, '/')
      return oldNormalizeLink.bind(this)(url)
    }
  })(md.normalizeLink)
}