HTML parser and compiler
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
scripts
src
.babelrc
.eslintignore
.eslintrc.js
.flowconfig
.gitignore
README.md
package-lock.json
package.json

README.md

dogma-html-parser

HTML parser and compiler.

Installation

npm install dogma-html-parser

Usage

Parser

To parse an HTML string into an AST you can do the following:

import {parse} from 'dogma-html-parser'

const html = '<div class="test">Foo bar</div>'
const ast = parse(html)

The above example will set the constant ast to the following AST:

{
  "attributes": {
    "class": "test"
  },
  "children": [
    {
      "text": "Foo bar",
      "type": "text"
    }
  ],
  "name": "div",
  "type": "element"
}

It is worth noting the parser tries to be forgiving in terms of invalid whitespace, and by default will strip out unnecessary whitespace that doesn't actually get rendered by browsers. For example if you parse then compile the following:

< div > Test < /div >

You'll end up with:

<div>Test</div>

Compiler

The compiler simply takes an AST and converts it to an HTML string like so:

import {compile} from 'dogma-html-parser'

const ast = {
  attributes: {
    'class': 'test',
  },
  children: [
    {
      text: 'Foo bar',
      type: 'text',
    },
  ],
  name: 'div',
  type: 'element',
}

const html = compile(ast)

The above example will set the constant html to the following HTML string:

<div class="test">Foo bar</div>