useref HTML Build Block Parser

1.4.4 · active · verified Tue Apr 21

useref is a JavaScript library designed to parse HTML files and replace special "build blocks" with optimized references. Extracted from the `grunt-useref` plugin, it provides a standalone utility for integrating into web build processes. The current stable version is 1.4.4, with releases appearing to be on an as-needed basis, focusing on stability and bug fixes as indicated by the versioning. Its primary differentiator is its ability to identify and process `<!-- build:<type> <path> -->...<!-- endbuild -->` comments, consolidating multiple script or link tags into a single optimized reference, and supporting custom block types for advanced processing. It also preserves IE conditional comments. This functionality is crucial for web performance optimization workflows where assets are concatenated and minified.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse an HTML string, transform build blocks into consolidated references, and retrieve the map of original assets to their optimized targets.

const useref = require('useref');

const sampleHtml = `
<html>
<head>
  <!-- build:css css/combined.css -->
  <link href="css/one.css" rel="stylesheet">
  <link href="css/two.css" rel="stylesheet">
  <!-- endbuild -->
</head>
<body>
  <!-- build:js scripts/combined.js -->
  <script type="text/javascript" src="scripts/one.js"></script>
  <script type="text/javascript" src="scripts/two.js"></script>
  <!-- endbuild -->

  <!-- build:js scripts/async.js async data-foo="bar" -->
  <script type="text/javascript" src="scripts/three.js"></script>
  <script type="text/javascript" src="scripts/four.js"></script>
  <!-- endbuild -->
</body>
</html>
`;

const [resultHtml, assetsMap] = useref(sampleHtml);

console.log("Transformed HTML:");
console.log(resultHtml);
console.log("\nIdentified Assets:");
console.log(JSON.stringify(assetsMap, null, 2));

/*
Example resultHtml output:
<html>
<head>
  <link rel="stylesheet" href="css/combined.css"/>
</head>
<body>
  <script src="scripts/combined.js"></script>
  <script src="scripts/async.js" async data-foo="bar" ></script>
</body>
</html>
*/

/*
Example assetsMap output:
{
  "css": {
    "css/combined.css": {
      "assets": [
        "css/one.css",
        "css/two.css"
      ]
    }
  },
  "js": {
    "scripts/combined.js": {
      "assets": [
        "scripts/one.js",
        "scripts/two.js"
      ]
    },
    "scripts/async.js": {
      "assets": [
        "scripts/three.js",
        "scripts/four.js"
      ]
    }
  }
}
*/

view raw JSON →