UNPKG

2.71 kBMarkdownView Raw
1# posthtml-parser
2[![npm version](https://badge.fury.io/js/posthtml-parser.svg)](http://badge.fury.io/js/posthtml-parser)
3[![Build Status](https://travis-ci.org/posthtml/posthtml-parser.svg?branch=master)](https://travis-ci.org/posthtml/posthtml-parser?branch=master)
4[![Coverage Status](https://coveralls.io/repos/posthtml/posthtml-parser/badge.svg?branch=master)](https://coveralls.io/r/posthtml/posthtml-parser?branch=master)
5
6Parse HTML/XML to [PostHTML AST](https://github.com/posthtml/posthtml-parser#posthtml-ast-format).
7More about [PostHTML](https://github.com/posthtml/posthtml#readme)
8
9## Install
10
11[NPM](http://npmjs.com) install
12```
13$ npm install posthtml-parser
14```
15
16## Usage
17
18#### Input HTML
19```html
20<a class="animals" href="#">
21 <span class="animals__cat" style="background: url(cat.png)">Cat</span>
22</a>
23```
24```js
25const parser = require('posthtml-parser')
26const fs = require('fs')
27const html = fs.readFileSync('path/to/input.html').toString()
28
29console.log(parser(html)) // Logs a PostHTML AST
30```
31
32#### input HTML
33```html
34<a class="animals" href="#">
35 <span class="animals__cat" style="background: url(cat.png)">Cat</span>
36</a>
37```
38
39#### Result PostHTMLTree
40```js
41[{
42 tag: 'a',
43 attrs: {
44 class: 'animals',
45 href: '#'
46 },
47 content: [
48 '\n ',
49 {
50 tag: 'span',
51 attrs: {
52 class: 'animals__cat',
53 style: 'background: url(cat.png)'
54 },
55 content: ['Cat']
56 },
57 '\n'
58 ]
59}]
60```
61
62## PostHTML AST Format
63
64Any parser being used with PostHTML should return a standard PostHTML [Abstract Syntax Tree](https://www.wikiwand.com/en/Abstract_syntax_tree) (AST). Fortunately, this is a very easy format to produce and understand. The AST is an array that can contain strings and objects. Any strings represent plain text content to be written to the output. Any objects represent HTML tags.
65
66Tag objects generally look something like this:
67
68```js
69{
70 tag: 'div',
71 attrs: {
72 class: 'foo'
73 },
74 content: ['hello world!']
75}
76```
77
78Tag objects can contain three keys. The `tag` key takes the name of the tag as the value. This can include custom tags. The optional `attrs` key takes an object with key/value pairs representing the attributes of the html tag. A boolean attribute has an empty string as its value. Finally, the optional `content` key takes an array as its value, which is a PostHTML AST. In this manner, the AST is a tree that should be walked recursively.
79
80## Options
81
82### `directives`
83Type: `Array`
84Default: `[{name: '!doctype', start: '<', end: '>'}]`
85Description: *Adds processing of custom directives*
86
87## License
88
89[MIT](LICENSE)