deps-html

get/replace the external dependencies of an HTML document

Usage no npm install needed!

<script type="module">
  import depsHtml from 'https://cdn.skypack.dev/deps-html';
</script>

README

deps-html

NPM version build status Test coverage

Parse the external dependencies of an HTML string as well as optionally replace them. Useful for build systems and package managers that need to rewrite URLs.

var deps = require('deps-html');

var string = '<link rel="stylesheet" href="normalize.css">';
// build the node tree
var ast = deps.parse(string);
// parse all the dependencies
var matches = deps.extract(ast);
// rewrite the `href`s
matches.forEach(function (dep) {
  if (dep.type === 'stylesheet' && dep.path === 'normalize.css') {
    dep.attr.value = './normalize.css';
  }
})
// return the new HTML
var html = deps.stringify(ast)
// html === '<link rel="stylesheet" href="./normalize.css">'

API

var ast = deps.parse(string)

Returns a parse5 tree.

var matches = deps.extract(ast)

Parses all the relevant dependencies from the document. Each match has the following properties:

  • path - the href or src attribute value
  • type - the type of dependency. The current types are:
    • <script>
    • <module>
    • <style>
    • <link>
      • ref="import"
      • ref="stylesheet"
    • <img>
    • svg xlink
  • node- the parse5 node for this dependency
  • attr - the raw parse5 attribute for the node containing href or src. Set attr.value= to change the value of the URL.

You are expected to use a module such as parse5-utils to manipulate the HTML elements.

var html = deps.stringify(ast)

Stringify the AST, keeping the relevant styles intact. It doesn't keep everything intact, which is annoying, but most of the styles remain intact.