0.1.0 • Published 10 months ago

html-esc v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

html-esc

minzip size badge

JavaScript Template Literal Tag that converts to HTML-escaped content. Eg. html`<div>${myVar}</div>`.

Barebones (and tiny, <50 lines of code) alternative to lit-html and htl, ideal for use in web components or to template in Vanilla/no build JavaScript.

It's ready for use straight in the browser via CDN (or copy-pasting into your project).

<script type="importmap">
  { "imports": { "html-esc": "https://esm.sh/html-esc" } }
</script>
<script type="module">
  import { html } from "html-esc";
  const message = "<strong>strong but will get escaped</strong>";
  document.body.innerHTML = html`<div>I'm ${message}</div>`;
</script>

Or via npm (assuming you want to use a bundler).

npm i html-esc

Why is this necessary?

htl has a great section on this: htl - why not concatenate?.

In short: values containing certain characters are not safe to be interpolated for cross-site scripting ("XSS") reasons and content display reasons (eg. & having special meaning in HTML).

Credit

Credit to developit/vhtml and dodoas/stringjsx for:

  • HTML entity escape function
  • the approach to tracking "already seen sanitized strings", this allows for avoiding "double escaping" ie. this renders as expected: html`<div>${html`<div>html-tagged</div>`}`

Requirements

  • Node 20
  • npm v8+

Setup

  1. Clone the repository
  2. Run npm install installs all required dependencies.

npm scripts

  • npm test will run tests using the Node.js test runner and the node:test module.
  • npm run format will run prettier on all the examples files (and tests).

LICENSE

Code is licensed under the MIT License.

0.1.0

10 months ago

0.0.3

10 months ago

0.0.2

10 months ago

0.0.1

10 months ago