htmljs-parser
An HTML parser with super powers used by Marko.
Installation
npm install htmljs-parser
Creating A Parser
First we must create a parser instance and pass it some handlers for the various parse events shown below.
Each parse event is called a Range
and is an object with start and end properties which are zero-based offsets from the beginning of th parsed code.
Additional meta data and nested ranges are exposed on some events shown below.
You can get the raw string from any range using parser.read(range)
.
import { createParser, ErrorCode, TagType } from "htmljs-parser";
const parser = createParser({
onError(range) {
range.code;
range.message;
},
onText(range) {},
onPlaceholder(range) {
range.escape;
range.value;
},
onComment(range) {
range.value;
},
onCDATA(range) {
range.value;
},
onDoctype(range) {
range.value;
},
onDeclaration(range) {
range.value;
},
onScriptlet(range) {
range.block;
range.value;
},
onOpenTagStart(range) {}
onOpenTagName(range) {
range.quasis;
range.expressions;
switch (parser.read(range)) {
case "area":
case "base":
case "br":
case "col":
case "embed":
case "hr":
case "img":
case "input":
case "link":
case "meta":
case "param":
case "source":
case "track":
case "wbr":
return TagType.void;
case "html-comment":
case "script":
case "style":
case "textarea":
return TagType.text;
case "class":
case "export":
case "import":
case "static":
return TagType.statement;
}
return TagType.html;
},
onTagShorthandId(range) {
range.quasis;
range.expressions;
},
onTagShorthandClass(range) {
range.quasis;
range.expressions;
},
onTagVar(range) {
range.value;
},
onTagArgs(range) {
range.value;
},
onTagParams(range) {
range.value;
},
onAttrName(range) {},
onAttrArgs(range) {
range.value;
},
onAttrValue(range) {
range.bound;
range.value;
},
onAttrMethod(range) {
range.params;
range.params.value;
range.body;
range.body.value;
},
onAttrSpread(range) {
range.value;
},
onOpenTagEnd(range) {
range.selfClosed;
},
onCloseTagStart(range) {},
onCloseTagName(range) {},
onCloseTagEnd(range) {},
});
Finally after setting up the parser with it's handlers, it's time to pass in some source code to parse.
parser.parse("<div></div>");
Parser Helpers
The parser instance provides a few helpers to make it easier to work with the parsed content.
parser.read(range);
parser.positionAt(offset);
parser.locationAt(range);
Code of Conduct
This project adheres to the eBay Code of Conduct. By participating in this project you agree to abide by its terms.