-
Notifications
You must be signed in to change notification settings - Fork 3
/
process-html.js
executable file
·32 lines (28 loc) · 964 Bytes
/
process-html.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
const path = require('path')
const toVfile = require('to-vfile')
const unified = require('unified')
const parseHtml = require('rehype-parse')
const outputHtml = require('rehype-stringify')
const findUrls = require('rehype-url-inspector')
function relativePath (file, url = '') {
const relativePrefix = path.relative(file.dirname, file.cwd) || null
return relativePrefix ? relativePrefix + url : url[0] === '/' ? url.substr(1) : url
}
function inspectEach ({ url, node, file }) {
if (url === '/' || url.match(/^\/[^/]/)) {
if (node.properties.href) {
node.properties.href = relativePath(file, node.properties.href)
}
if (node.properties.src) {
node.properties.src = relativePath(file, node.properties.src)
}
}
}
const processor = unified()
.use(parseHtml)
.use(findUrls, { inspectEach })
.use(outputHtml)
module.exports = async function (vfile) {
const res = await processor.process(vfile)
toVfile.writeSync(res)
}