{"id":13306,"library":"htmlparser2-svelte","title":"HTMLParser2 Svelte","description":"htmlparser2-svelte is a robust and forgiving HTML, Svelte, XML, and RSS parser for JavaScript environments, currently at version 4.1.1. It enhances the core `htmlparser2` library by adding native support for Svelte-specific syntax, particularly JavaScript expressions within tag attributes (e.g., `on:click={() => ...}`). The library offers both a synchronous `Parser` interface and an asynchronous `WritableStream` for processing streaming input, making it suitable for a wide range of parsing tasks. Its design emphasizes speed and fault tolerance, making it ideal for parsing real-world, potentially malformed HTML, and especially beneficial for tooling that needs to understand Svelte component structures. Releases appear to be driven by feature additions and maintenance, with 4.1.0 introducing support for JS expressions in attributes.","status":"active","version":"4.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/alexprey/htmlparser2","tags":["javascript","html","parser","streams","xml","dom","rss","feed","atom","typescript"],"install":[{"cmd":"npm install htmlparser2-svelte","lang":"bash","label":"npm"},{"cmd":"yarn add htmlparser2-svelte","lang":"bash","label":"yarn"},{"cmd":"pnpm add htmlparser2-svelte","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used to construct a DOM tree from the parsed HTML events. While historically bundled, it's recommended to install and use it separately for the latest features and maintenance.","package":"domhandler","optional":true},{"reason":"Provides utility functions for manipulating the DOM tree generated by `domhandler`. Recommended alongside `domhandler`.","package":"domutils"}],"imports":[{"note":"For modern ESM projects, import `Parser` as a named export. The CommonJS pattern `htmlparser2.Parser` is shown in older examples but can lead to issues in ESM environments.","wrong":"const htmlparser2 = require('htmlparser2-svelte'); const parser = new htmlparser2.Parser(...);","symbol":"Parser","correct":"import { Parser } from 'htmlparser2-svelte';"},{"note":"Use `WritableStream` for processing streaming HTML content, similar to Node.js streams. Ensure it's imported as a named export.","wrong":"const htmlparser2 = require('htmlparser2-svelte'); const stream = new htmlparser2.WritableStream(...);","symbol":"WritableStream","correct":"import { WritableStream } from 'htmlparser2-svelte';"},{"note":"Directly import `parseFeed` for RSS/Atom/RDF feed parsing. While convenient, consider dedicated libraries like `node-feedparser` for more robust feed handling.","wrong":"const htmlparser2 = require('htmlparser2-svelte'); const feed = htmlparser2.parseFeed(content);","symbol":"parseFeed","correct":"import { parseFeed } from 'htmlparser2-svelte';"},{"note":"Import types explicitly when working with TypeScript for better type safety and autocompletion for parser options and handlers.","symbol":"ParserOptions","correct":"import type { ParserOptions } from 'htmlparser2-svelte';"}],"quickstart":{"code":"import { Parser } from 'htmlparser2-svelte';\n\nconst svelteCode = `\n<script lang=\"ts\">\n    let count = 0;\n    function handleClick() {\n        count += 1;\n        console.log('Button clicked:', count);\n    }\n</script>\n\n<div class=\"app\">\n    <h1>Svelte Parser Example</h1>\n    <button type=\"button\" on:click={() => handleClick()} title={\"Click count is \" + count}>\n        Click me {count} times!\n    </button>\n    <p>This paragraph has some <span>inline</span> text.</p>\n</div>\n`;\n\nconst parser = new Parser(\n    {\n        onopentag(name, attribs) {\n            console.log(`Opened tag: <${name}> with attributes:`, attribs);\n        },\n        ontext(text) {\n            const trimmedText = text.trim();\n            if (trimmedText.length > 0) {\n                console.log(`Text content: \"${trimmedText}\"`);\n            }\n        },\n        onclosetag(tagname) {\n            console.log(`Closed tag: </${tagname}>`);\n        },\n        onprocessinginstruction(name, data) {\n            console.log(`Processing instruction: ${name} -> ${data}`);\n        }\n    },\n    {\n        decodeEntities: true,\n        curlyBracesInAttributes: true, // Crucial for Svelte support\n        xmlMode: false // Parse as HTML\n    }\n);\n\nparser.write(svelteCode);\nparser.end();","lang":"typescript","description":"Demonstrates parsing a Svelte component template, including JavaScript expressions in attributes, using the callback API to log parsing events to the console."},"warnings":[{"fix":"Always pass `{ curlyBracesInAttributes: true }` as the second argument to `new Parser()` or `new WritableStream()` when parsing Svelte templates.","message":"To correctly parse Svelte-specific syntax, such as JavaScript expressions within tag attributes (e.g., `on:click={() => ...}`), you *must* enable the `curlyBracesInAttributes: true` option in the parser configuration. Without this, Svelte expressions will be treated as regular attribute values or malformed HTML, leading to incorrect parsing.","severity":"gotcha","affected_versions":">=4.1.0"},{"fix":"Install `domhandler` and `domutils` separately via `npm install domhandler domutils` and import them directly to build and manipulate the DOM tree.","message":"The `DomHandler` utility, which provides DOM tree construction, was originally bundled but has since been moved to its own dedicated `domhandler` package. While `htmlparser2-svelte` might still bundle an older version for compatibility, relying on the separate `domhandler` package directly is recommended for the latest features and maintenance.","severity":"deprecated","affected_versions":">=3.x"},{"fix":"For advanced feed parsing, evaluate dedicated libraries like `node-feedparser` instead of the built-in `parseFeed` method.","message":"While `htmlparser2-svelte` offers a `parseFeed` utility, the documentation notes that more robust and actively maintained alternatives like `danmactough/node-feedparser` exist. For critical applications requiring comprehensive RSS/Atom/RDF feed parsing, consider using specialized libraries for better compliance and feature sets.","severity":"gotcha","affected_versions":"*"},{"fix":"Update `require('pkg')` statements to `import { Symbol } from 'pkg'` for better compatibility with ESM.","message":"Many examples for `htmlparser2-svelte` (and its base `htmlparser2`) use CommonJS `require()` syntax (e.g., `const htmlparser2 = require('htmlparser2-svelte');`). In modern JavaScript environments or when using bundlers that support ESM, prefer named imports like `import { Parser } from 'htmlparser2-svelte';` to leverage tree-shaking and standard module resolution.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For CommonJS, use `const { Parser } = require('htmlparser2-svelte');`. For ESM, use `import { Parser } from 'htmlparser2-svelte';`.","cause":"Attempting to instantiate `Parser` using a CommonJS `require` that doesn't correctly export named members, or in an ESM context where `htmlparser2` is imported as a default object.","error":"TypeError: htmlparser2.Parser is not a constructor"},{"fix":"Ensure `htmlparser2-svelte` is correctly installed and imported, not `htmlparser2`, when using Svelte-specific parsing options.","cause":"This error occurs when the `curlyBracesInAttributes` option is passed to the original `htmlparser2` package, which does not support Svelte-specific syntax, instead of `htmlparser2-svelte`.","error":"Error: Unknown option: curlyBracesInAttributes"},{"fix":"Include `{ curlyBracesInAttributes: true }` in the options object when creating a `Parser` or `WritableStream` instance for Svelte content.","cause":"The `curlyBracesInAttributes` option, essential for Svelte syntax, was not enabled when initializing the parser.","error":"Svelte component attributes with `{@expression}` or `{expression}` are not correctly parsed."},{"fix":"Ensure you are importing and instantiating `WritableStream` for streaming operations (`import { WritableStream } from 'htmlparser2-svelte'; new WritableStream(...)`), as `Parser` does not directly support `pipe()`.","cause":"This typically happens when trying to use Node.js `Stream.pipe()` functionality on a `Parser` instance, which is for direct string input, rather than a `WritableStream` instance, or if `WritableStream` was not imported correctly.","error":"TypeError: Cannot read properties of undefined (reading 'pipe')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}