npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

html-svelte-parser

v1.0.0

Published

HTML to Svelte parser.

Downloads

563

Readme

html-svelte-parser

HTML to Svelte parser that works on both the server (Node.js) and the client (browser).

To replace an element with a svelte component, check out the processNode option.

Example

Paragraph.svelte

<p><slot /></p>

App.svelte

<script>
	import { Html, isTag } from 'html-svelte-parser';
	import Paragraph from './Paragraph.svelte';
</script>

<Html
	html="<p>Hello, World!</p>"
	processNode={node => {
		if (isTag(node) && node.name === 'p') {
			return { component: Paragraph };
		}
	}}
/>

<!--
	Equivalent to:

	<Paragraph>Hello, World!</Paragraph>
-->

Install

Install the NPM package html-svelte-parser with your favorite package manager:

npm install html-svelte-parser
# pnpm add html-svelte-parser
# yarn add html-svelte-parser

Usage

<script>
	import { Html } from 'html-svelte-parser';
</script>

<!-- Single element: -->
<Html html="<h1>single</h1>" />

<!-- Multiple elements: -->
<ul>
	<Html html="<li>Item 1</li><li>Item 2</li>" />
</ul>

<!-- Nested elements: -->
<Html html="<div><p>Lorem ipsum</p></div>" />

<!-- Element with attributes: -->
<Html
	html={`<hr id="foo" class="bar" data-attr="baz" custom="qux" style="top:42px;">`}
/>

processNode

The processNode option is a function that allows you to modify or remove a DOM node or replace it with a svelte component. It receives one argument which is domhandler's node (either Element or Text):

<Html
	html="<br>"
	processNode={domNode => {
		console.dir(domNode, { depth: null });
	}}
/>

Console output:

Element {
  type: 'tag',
  parent: null,
  prev: null,
  next: null,
  startIndex: null,
  endIndex: null,
  children: [],
  name: 'br',
  attribs: {}
}

Modify/remove nodes

You can directly modify the DOM nodes or remove them by returning false:

<script>
	import { Html, isTag, Text } from 'html-svelte-parser';

	const html = `
		<p id="remove">remove me</p>
		<p id="keep">keep me</p>
	`;

	/** @type {import('html-svelte-parser').ProcessNode} */
	const processNode = domNode => {
		if (isTag(domNode)) {
			if (domNode.attribs.id === 'remove') {
				return false;
			}

			if (domNode.attribs.id === 'keep') {
				domNode.attribs.id = 'i-stay';
				domNode.children = [new Text('i stay!')];
			}
		}
	};
</script>

<Html {html} {processNode} />

<!--
	Equivalent to:

	<p id="i-stay">i stay!</p>
-->

Replace nodes

To replaced a DOM node with a svelte component return an object with a component property.
Additionally the object can have a props property.

Span.svelte

<span {...$$props}><slot /></span>

App.svelte

<script>
	import { Html, isTag, Text } from 'html-svelte-parser';
	import Span from './Span.svelte';

	const html = `<p id="replace">text</p>`;

	/** @type {import('html-svelte-parser').ProcessNode} */
	const processNode = domNode => {
		if (isTag(domNode) && domNode.attribs.id === 'replace') {
			domNode.children = [new Text('replaced')];
			return { component: Span, props: { class: 'my-span' } };
		}
	};
</script>

<Html {html} {processNode} />

<!--
	Equivalent to:

	<span class="my-span">replaced</span>
-->

Usage with sveltekit

html-svelte-parser exports more than just the Html component, which makes it possible to delegate the work of parsing and processing to the server. An added bonus, you ship less code to the client.

components/Button.svelte

<script>
	/** @type {string | undefined} */
	export let href = undefined;

	/** @type {'button' | 'submit' | 'reset'}*/
	export let type = 'button';
</script>

{#if href}
	<a {...$$restProps} {href}><slot /></a>
{:else}
	<button {...$$restProps} {type}><slot /></button>
{/if}

+page.server.js

import { isTag, parse } from 'html-svelte-parser';

/** @type {import('./$types').PageServerLoad} */
export const load = () => {
	return {
		content: parse(
			`<p><a class="btn" href="https://svelte.dev/">Svelte</a> rocks</p>`,
			{
				processNode(node) {
					if (
						isTag(node) &&
						node.name === 'a' &&
						node.attribs.class?.split(/\s/).includes('btn')
					) {
						// We use a `string` for the `component` property.
						return { component: 'Button', props: node.attribs };
					}
				},
			},
		),
	};
};

+page.js

import { loadComponents } from 'html-svelte-parser';

/** @type {import('./$types').PageLoad} */
export const load = ({ data }) => ({
	content: loadComponents(data.content, componentName => {
		// `componentName` is the `component` we returned in `+page.server.js`
		return import(`./components/${componentName}.svelte`);
	}),
});

+page.svelte

<script>
	import { Renderer } from 'html-svelte-parser';

	/** @type {import('./$types').PageData} */
	export let data;
</script>

<Renderer {...data.content} />

<!--
	Equivalent to:

	<p><Button class="btn" href="https://svelte.dev/">Svelte</Button> rocks</p>
-->

Named slots

What if your component has named slots? Unfortunately it is currently not possible to render named slots dynamically with svelte.
Fortunately, we can work around the problem with a wrapper component and the Renderer component.

Button.svelte

<script>
	/** @type {string | undefined} */
	export let href = undefined;

	/** @type {'button' | 'submit' | 'reset'}*/
	export let type = 'button';
</script>

{#if href}
	<a {...$$restProps} {href}><slot /></a>
{:else}
	<button {...$$restProps} {type}><slot /></button>
{/if}

Card.svelte

<div class="card">
	{#if $$slots.title}
		<div class="title"><slot name="title" /></div>
	{/if}

	<div class="content"><slot /></div>

	{#if $$slots.actions}
		<div class="actions"><slot name="actions" /></div>
	{/if}
</div>

CardWrapper.svelte
This is our wrapper component.

<script>
	import { Renderer } from 'html-svelte-parser';
	import Card from './Card.svelte';

	/** @type {import('html-svelte-parser').RendererProps} */
	export let title;

	/** @type {import('html-svelte-parser').RendererProps} */
	export let content;

	/** @type {import('html-svelte-parser').RendererProps} */
	export let actions;
</script>

<Card>
	<Renderer slot="title" {...title} />
	<Renderer {...content} />
	<Renderer slot="actions" {...actions} />
</Card>

App.svelte

<script>
	import { Html, isTag } from 'html-svelte-parser';
	import Button from './Button.svelte';
	import CardWrapper from './CardWrapper.svelte';

	const html = `
		<div class="card">
			<h1 class="card--title">My Card</h1>

			<div class="card--content">
				<p>This gets replaced with a nice Card component</p>
				<p><a href="https://svelte.dev/">Svelte</a> is cool.</p>
			</div>

			<div class="card--actions">
				<a class="btn" href="/whatever">Call to action</a>
			</div>
		</div>
	`;

	// lets define some helpers

	const hasClass = (
		/** @type {import('domhandler').Element} */ node,
		/** @type {string} */ className,
	) => node.attribs.class?.split(/\s/).includes(className);

	const findChildWithClass = (
		/** @type {import('domhandler').ParentNode} */ node,
		/** @type {string} */ className,
	) =>
		/** @type {import('domhandler').Element | undefined} */ (
			node.children.find(child => isTag(child) && hasClass(child, className))
		);

	/** @type {import('html-svelte-parser').ProcessNode} */
	const processNode = node => {
		if (!isTag(node)) return;

		// add attributes to external links
		if (node.name === 'a' && !node.attribs.href?.startsWith('/')) {
			node.attribs.target = '_blank';
			node.attribs.rel = 'noreferrer nofollow';
		}

		if (hasClass(node, 'card')) {
			return {
				component: CardWrapper,

				// don't process child nodes / no "default" slot for `CardWrapper`
				noChildren: true,

				// transform specific child nodes into props that get passed to
				// `CardWrapper` and can be rendered in a named slot with `Renderer`
				rendererProps: {
					// even if `findChildWithClass` returns undefined, `CardWrapper`
					// still gets a `title` prop
					title: findChildWithClass(node, 'card--title'),

					// for `content` and `actions`, we want only the children of the
					// selected element to be rendered
					content: findChildWithClass(node, 'card--content')?.children,
					actions: findChildWithClass(node, 'card--actions')?.children,
				},
			};
		}

		if (hasClass(node, 'btn')) {
			return { component: Button, props: node.attribs };
		}
	};
</script>

<Html {html} {processNode} />

<!--
	Equivalent to

	<Card>
		<svelte:fragment slot="title">
			<h1 class="card--title">My Card</h1>
		</svelte:fragment>

		<p>This gets replaced with a nice Card component</p>
		<p><a href="https://svelte.dev/" target="_blank" rel="noreferrer nofollow">Svelte</a> is cool.</p>

		<svelte:fragment slot="actions">
			<Button class="btn" href="/whatever">Call to action</Button>
		</svelte:fragment>
	</Card>
-->

TODO

  • API docs
  • cleanup tests & more tests
  • GH page

Credits

Inspired by html-react-parser and html-to-react.