Skip to content
0

HTML Parser

介绍一下 HTML 转换的方法

parse5

使用 inikulin/parse5 来解析 HTML,这是一款 HTML5 的语法解析器,将 HTML 字符串转换为 AST

const parse5 = require('parse5');

const document = parse5.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>');

console.log(document.childNodes[1].tagName); //> 'html'

此方法功能较为完善,但比较复杂,所有还有一款更简单方法供选择:

hast家族

例如,我们的目的仅仅是修改 svg 标签的属性,可以使用如下方法:

// pnpm i hast-util-to-html hast-util-from-html @types/hast -D
import { toHtml } from 'hast-util-to-html'
import { fromHtml } from 'hast-util-from-html'
import type { Element } from 'hast'

const root = fromHtml(svgString, { fragment: true })
const svg = root.children[0] as Element
svg.properties = {
  ...svg.properties,
  // Remove svg tag's height property
  height: '',
  // Add margin Y to better style
  style: 'margin: 16px 0'
}
const result = toHtml(svg)

调用 fromHtml 可以将 HTML 字符串转化为 hast 标准的 AST,利用 toHtml,将 AST 转回 HTML。

除此之外,我们也可以使用 hastscript ,进行新增节点的操作

// pnpm i hastscript -D
import { h } from 'hastscript'

const titleWrapper = h('div', {
  class: 'title',
}, [svgString])

const result = toHtml(titleWrapper)

Released under the MIT License.