入门使用
import posthtml from 'posthtml'
const sourceCode = `
<html>
<body>
<p class="wow">OMG</p>
</body>
</html>
`
const { html } =await posthtml()
.use((tree) => {
plugin(tree, {
moduleName: this.name,
})
})
.process(sourceCode);
console.log(html);
编写 PostHTML 插件?
PostHTML 的插件本质上就是一个函数,就接受一个参数,即 PostHTML 工厂处理好的 PostHTMLTree
,插件要做的就是对这个 tree
进行修改。
PostHTML 提供了两个方法来遍历 tree
:
- .match(matcher, callback):matcher 可以是对象、字符串或者正则表达式,
match
方法会遍历整个 tree,寻找与 matcher 匹配的 node,然后将 node 传递给 callback,我们可以在 callback 中修改 node 实现我们想要的功能; - .walk(callback):比起 match,walk 是一个更加通用的方法,遍历 tree 中的每一个节点,传递给 callback。
下面是一个简单的插件:
module.exports = function pluginName(tree, opts) {
// do something for tree
tree.match({ tag: 'img' }, function(node) {
node = Object.assign(node, { attrs: { class: opts.moduleName } }});
return {
tag: 'span',
attrs: { class: 'img-wrapper' },
content: node
}
});
};