we-rich

1.0.2 • Public • Published

We Rich

Parse HTML into Weapp rich-text Nodes

HTML转小程序 rich-text 控件节点

npm

Usage

Node

npm install we-rich
import fs from 'fs'
import {parse} from 'we-rich'
const html = fs.readFileSync('/webpage.html', {encoding: 'utf8'})
const json = parse(html)
console.log('👉', json)

Weapp

下载 we-rich.js

Example Input/Output

<div class='post post-featured'>
  <p>Himalaya parsed me...</p>
  <!-- ...and I liked it. -->
</div>
[{
  type: 'element',
  tagName: 'div',
  attributes: [{
    key: 'class',
    value: 'post post-featured'
  }],
  children: [{
    type: 'element',
    tagName: 'p',
    attributes: [],
    children: [{
      type: 'text',
      content: 'Himalaya parsed me...'
    }]
  }, {
    type: 'comment',
    content: ' ...and I liked it. '
  }]
}]

Note: In this example, text nodes consisting of whitespace are not shown for readability.

Features

Synchronous

Himalaya transforms HTML into JSON, that's it. Himalaya is synchronous and does not require any complicated callbacks.

Handles Weirdness

Himalaya handles a lot of HTML's fringe cases, like:

  • Closes unclosed tags <p><b>...</p>
  • Ignores extra closing tags <span>...</b></span>
  • Properly handles void tags like <meta> and <img>
  • Properly handles self-closing tags like <input/>
  • Handles <!doctype> and <-- comments -->
  • Does not parse the contents of <script>, <style>, and HTML5 <template> tags

Preserves Whitespace

Himalaya does not cut corners and returns an accurate representation of the HTML supplied. To remove whitespace, post-process the JSON; check out an example script.

Going back to HTML

Himalaya provides a stringify method. The following example parses the HTML to JSON then parses the JSON back into HTML.

import fs from 'fs'
import {parse, stringify} from 'himalaya'
 
const html = fs.readFileSync('/webpage.html', {encoding: 'utf8'})
const json = parse(html)
fs.writeFileSync('/webpage.html', stringify(json))

此项目基于 himalaya

Package Sidebar

Install

npm i we-rich

Weekly Downloads

12

Version

1.0.2

License

ISC

Last publish

Collaborators

  • tans