Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

minify-html-literals

Package Overview
Dependencies
Maintainers
1
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

minify-html-literals

Minify HTML template literal strings

  • 1.0.6
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
18K
decreased by-8.55%
Maintainers
1
Weekly downloads
 
Created
Source

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.

PropertyTypeDefaultDescription
fileNamestringRequired. The name of the file, used for syntax parsing and source maps.
minifyOptions?html-minifier optionsdefaultMinifyOptionsDefaults to production-ready minification.
shouldMinify?functiondefaultShouldMinifyA function that determines whether or not a template should be minified. Defaults to minify all tagged templates whose tag name contains "html" (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.

PropertyTypeDefaultDescription
generateSourceMap?boolean or `(ms: MagicString, fileName: string) => SourceMapundefined`defaultGenerateSourceMap
strategy?objectdefaultStrategyAn object with methods defining how to minify HTML. The default strategy uses html-minifier.
validate?boolean or objectdefaultValidationSet 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?functionparse-literalsOverride the function used to parse template literals from a source string.
parseLiteralsOptions?objectAdditional options to pass to parseLiterals()
MagicString?functionMagicStringOverride the MagicString-like constructor to use for manipulating the source string and generating source maps.

Customization Examples

Do not minify CSS

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

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

Minify non-tagged templates

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

minifyHTMLLiterals(
  `function render() {
    return html\`
      <h1>This tagged template is minified</h1>
      \${\`
        <div>and so is this non-tagged template</div>
      \`}
    \`;
  }`,
  {
    fileName: 'render.js',
    shouldMinify(template) {
      return (
        defaultShouldMinify(template) ||
        template.parts.some(part => {
          return part.text.includes('<div>');
        })
      );
    }
  }
);

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
    });
  }
});

Keywords

FAQs

Package last updated on 03 Oct 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc