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

minify-html-literals

v1.3.5

Published

Minify HTML template literal strings

Downloads

56,699

Readme

minify-html-literals

Minify HTML markup inside JavaScript template literal strings.

npm Build Status Coverage Status

Why?

Template literals are often used in JavaScript to write HTML and CSS markup (ex. lit-html). This library allows a developer to minify markup that is normally ignored by JavaScript minifiers.

Usage

import { minifyHTMLLiterals } from 'minify-html-literals';
// const minifyHTMLLiterals = require('minify-html-literals').minifyHTMLLiterals

const result = minifyHTMLLiterals(
  `function render(title, items) {
    return html\`
      <style>
        .heading {
          color: blue;
        }
      </style>
      <h1 class="heading">\${title}</h1>
      <ul>
        \${items.map(item => {
          return getHTML()\`
            <li>\${item}</li>
          \`;
        })}
      </ul>
    \`;
  }`,
  {
    fileName: 'render.js'
  }
);

console.log(result.code);
//  function render(title, items) {
//    return html`<style>.heading{color:#00f}</style><h1 class=heading>${title}</h1><ul>${items.map(item => {
//          return getHTML()`<li>${item}</li>`;
//        })}</ul>`;
//  }

console.log(result.map);
// {
//   "version": 3,
//   "file": "render.js.map",
//   "sources": ["render.js"],
//   "sourcesContent": [null],
//   "names": [],
//   "mappings": "AAAA;gBACgB,qDAMU,QAAQ,SAE1B;2BACmB,IACX,OAAO,KACb;WACC,KAEP;"
// }

ES5 Transpiling Warning

Be sure to minify template literals before transpiling to ES5. Otherwise, the API will not be able to find any template literal (`${}`) strings.

Supported Source Syntax

  • JavaScript
  • TypeScript

Options

Basic

The following options are common to typical use cases.

| Property | Type | Default | Description | | --------------------------- | -------------------------------------------------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | fileName | string | | Required. The name of the file, used for syntax parsing and source maps. | | minifyOptions? | html-minifier options | defaultMinifyOptions | Defaults to production-ready minification. | | minifyOptions?.minifyCSS? | clean-css options | defaultMinifyCSSOptions | Uses clean-css defaults. | | shouldMinify? | function | defaultShouldMinify | A function that determines whether or not an HTML template should be minified. Defaults to minify all tagged templates whose tag name contains "html" (case insensitive). | | shouldMinifyCSS? | function | defaultShouldMinifyCSS | A function that determines whether or not a CSS template should be minified. Defaults to minify all tagged templates whose tag name contains "css" (case insensitive). |

Advanced

All aspects of the API are exposed and customizable. The following options will not typically be used unless you need to change how a certain aspect of the API handles a use case.

| Property | Type | Default | Description | | ----------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | generateSourceMap? | boolean or (ms: MagicString, fileName: string) => SourceMap | undefined | defaultGenerateSourceMap | Set to false to disable source maps, or a custom function to control how source maps are generated from a MagicString instance. | | strategy? | object | defaultStrategy | An object with methods defining how to minify HTML. The default strategy uses html-minifier. | | validate? | boolean or object | defaultValidation | Set to false to disable strategy validation checks, or to a custom set of validation functions. This is only useful when implementing a custom strategy. | | parseLiterals? | function | parse-literals | Override the function used to parse template literals from a source string. | | parseLiteralsOptions? | object | | Additional options to pass to parseLiterals() | | MagicString? | function | MagicString | Override the MagicString-like constructor to use for manipulating the source string and generating source maps. |

Customization Examples

Minify non-tagged templates

This is particularly useful for libraries that define templates without using tags, such as Polymer's <dom-module>.

import { minifyHTMLLiterals, defaultShouldMinify } from 'minify-html-literals';

minifyHTMLLiterals(
  `
    template.innerHTML = \`
      <dom-module id="custom-styles">
        <style>
          html {
            --custom-color: blue;
          }
        </style>
      </dom-module>
    \`;
  `,
  {
    fileName: 'render.js',
    shouldMinify(template) {
      return (
        defaultShouldMinify(template) ||
        template.parts.some(part => {
          return part.text.includes('<dom-module>');
        })
      );
    }
  }
);

Do not minify CSS

import { minifyHTMLLiterals, defaultMinifyOptions } from 'minify-html-literals';

minifyHTMLLiterals(source, {
  fileName: 'render.js',
  minifyOptions: {
    ...defaultMinifyOptions,
    minifyCSS: false
  },
  shouldMinifyCSS: () => false
});

Modify generated SourceMap

minifyHTMLLiterals(source, {
  fileName: 'render.js',
  generateSourceMap(ms, fileName) {
    return ms.generateMap({
      file: `${fileName}-converted.map`, // change file name
      source: fileName,
      includeContent: true // include source contents
    });
  }
});