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

string-to-template-literal

v3.0.0

Published

๐Ÿ”  Like JSON.stringify(), but returns a template string

Downloads

47,426

Readme

Encode as template literal

๐Ÿ”  Like JSON.stringify(), but returns a template string

// In some HTTP service that generates a '<script>' to print Hamlet...
const hamlet = await readFile("hamlet.txt", "utf8");
const js = `console.log(${stringToTemplateLiteral(hamlet)})`;
console.debug(js);
// No '\n'; it's a multiline string! ๐Ÿ‘‡
// This is 'console.debug(js)' output from above ๐Ÿ‘†
console.log(`ACT I
SCENE I. Elsinore. A platform before the castle.
  FRANCISCO at his post. Enter to him BERNARDO
BERNARDO
  Who's there?
...`);

๐Ÿ“„ Escapes </script> sequences; safe to inject into <script> tags
๐Ÿคฉ Great for encoding text for embedding in JavaScript source text
๐Ÿค It's tiny; only 5 lines of code!
๐Ÿ“ฆ Slightly more space-efficient than JSON.stringify()

Installation

npm

You can install this package using npm, pnpm, Yarn, or your favorite npm package manager.

npm install string-to-template-literal

You can also import this package straight from an npm CDN if you're in your browser using native ES modules:

import {} from "https://esm.run/string-to-template-literal@^3.0.0";
import {} from "https://esm.sh/string-to-template-literal@^3.0.0";
/** @param {string} x */
function stringToTemplateLiteral(x = "") {
  x = `${x}`;
  const escaped = x.replace(/\\|`|\$(?={)|(?<=<)\//g, (y) => "\\" + y);
  return `\`${escaped}\``;
}

๐Ÿ‘ฉโ€โš–๏ธ This code is licensed under the 0BSD license so you don't need to include any license text. ๐Ÿ˜‰

Usage

Browser Node.js Deno

The stringToTemplateLiteral() function returns a wrapped string that is compatible with eval(), embedding in <script> tags, and embedding in .js files.

import stringToTemplateLiteral from "string-to-template-literal";

// Running in some serverless runtime like
// Vercel, Deno Deploy, AWS Lambda, etc.
async function handleIndexHTML(request) {
  const hamlet = await readFile("hamlet.txt", "utf8");
  const js = `console.log(${stringToTemplateLiteral(hamlet)})`;
  const html = `
    <p>Check your DevTools console for Hamlet!</p>
    <script>${js}</script>
  `;
  return new Response(html);
}

The best example of when you might want to use this package is when creating a source code string that you want to embed in your JavaScript application as raw text. Think something like a bundler that needs to embed a .txt file into a JavaScript source file or a dynamic HTML page that needs to inject some text into a <script> tag. You could use JSON.stringify() in all these cases, but your text may become unreadable to humans since JSON.stringify() forces everything on one line with lots of escapes that are not needed when using `template strings`.