posthtml 虚拟语法树(AST)解析器及插件介绍

作者: tww844475003 分类: 前端开发 发布时间: 2021-09-21 11:21

介绍

PostHTML 是一种使用 JS 插件转换 HTML/XML 的工具。PostHTML 本身非常小。它仅包含一个 HTML 解析器、一个 HTML 节点树 API 和一个节点树字符串化器。

所有 HTML 转换都是由插件完成的。这些插件只是简单的小型 JS 函数,它们接收 HTML 节点树,对其进行转换,然后返回修改后的树。

依赖

名称描述
posthtml-parserParser HTML/XML to PostHTMLTree
posthtml-renderRender PostHTMLTree to HTML/XML

安装

npm i -D posthtml

使用

  • HTML/XML 转换 PostHTMLTree
// input.html
<ul class="ifrontend-list">
  <li class="react">react.js</li>
  <li class="vue">vue.js</li>
  <li class="angular">angular.js</li>
</ul>
const fs = require('fs')
const { parser } = require('posthtml-parser')

const html = fs.readFileSync('html/input.html', 'utf-8')
const result = parser(html)
console.log(result)
fs.writeFile('./ast.json', JSON.stringify(result), 'utf-8', function(error) {
  console.log('写入成功');
});

常用插件列表

  • posthtml-pug

将pug转化成html

  • posthtml-md

将md语法转化为html语法

  • posthtml-retext

根据规则转化自然语言(例如特定字符串转成emoji表情)

  • posthtml-head-elements

将JSON配置生成head元素内容

  • posthtml-include

引入html片段(实现html的模块化)

  • posthtml-modules

同上,而且她能实现vue中slot的效果

  • posthtml-inline-assets

将外部的css、js、图片等资源内联进html

  • posthtml-cache

在某标签的某属性值后增加随机查询参数

  • posthtml-spaceless

删除指定区域内标签之间的空格

  • posthtml-postcss

使用postcss处理html内的样式(style标签和内联样式)

  • posthtml-px2rem

在html内使用px2rem处理style标签和内联样式

  • posthtml-inline-css

可将外部样式或style标签内样式弄成内联样式

  • posthtml-collect-inline-styles

可将内联样式提取到style标签内

  • posthtml-style-to-file

可将内联样式和style标签内样式提取到独立文件内

  • posthtml-color-shorthand-hex-to-six-digit

将缩写的hex color转化成6个字符的格式

  • posthtml-minifier

压缩

  • htmlnano

同上

  • posthtml-remove-attributes

根据属性名或值去除指定属性

  • posthtml-remove-tags

去除指定名称的标签

  • Posthtml-remove-duplicates

根据标签名删除内容完全一样的标签

  • posthtml-transfomer

1.将标记的引用外部文件的script或link标签的内容,内联进html
2.将标记的标签删除
3.将标记的多个引用外部文件的script或link标签的内容,内联进html内的同一标签内

  • posthtml-tidy

整理html、清理无用的标签

插件使用

const posthtml = require('posthtml');

const html = `
  <component>
    <title>Super Title</title>
    <text>Awesome Text</text>
  </component>
`

const result = posthtml()
  .use(require('posthtml-custom-elements')())
  .process(html, { sync: true })
  .html

console.log(result)
const posthtml = require('posthtml')

const html = `
  <html>
    <body>
      <p class="wow">OMG</p>
    </body>
  </html>
`

posthtml(
  [
    require('posthtml-to-svg-tags')(),
    require('posthtml-extend-attrs')({
      attrsTree: {
        '.wow' : {
          id: 'wow_id',
          fill: '#4A83B4',
          'fill-rule': 'evenodd',
          'font-family': 'Verdana'
        }
      }
    })
  ])
  .process(html/*, options */)
  .then((result) =>  console.log(result.html))

前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注