Skip to content

feat: add transformPath option to transform matching attribute values#49

Merged
metonym merged 1 commit intomasterfrom
feature-content-attr
Nov 25, 2020
Merged

feat: add transformPath option to transform matching attribute values#49
metonym merged 1 commit intomasterfrom
feature-content-attr

Conversation

@metonym
Copy link
Copy Markdown
Collaborator

@metonym metonym commented Nov 24, 2020

#48

Features

  • expand attribute matchers (href, src) to include "content"
  • add optional transformPath method to modify matched attribute values for local file resolution

Usage

This is useful for preserving files with remote origin URLs and resolving them locally so they can be hashed.

Real world use case outlined in #48

Structure:

.
├── script.js
├──📁 build
│   ├── index.html
│   ├── image.[hash].png
│   └── 📁 assets
│       ├── small-image.[hash].png

Unprocessed HTML file:

<!-- build/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta property="og:image" content="https://example.com/image.[hash].png" />
    <meta property="twitter:image" content="https://example.com/assets/small-image.[hash].png" />
  </head>
  <body></body>
</html>

Post-build script:

// script.js
const fs = require("fs");
const posthtml = require("posthtml");
const { hash } = require("posthtml-hash");

const html = fs.readFileSync("./build/index.html");

posthtml()
  .use(
    hash({
      path: "processed",
      hashLength: 6,
      transformPath: (filepath) => {
        // removes the targeted remote origin URL when looking up the files locally
        return filepath.replace("https://example.com/", "");
      },
    })
  )
  .process(html)
  .then((result) => fs.writeFileSync("./build/index.html", result.html));

Processed HTML file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta property="og:image" content="https://example.com/image.1fa9a3.png">
    <meta property="twitter:image" content="https://example.com/assets/small-image.b354fd.png">
  </head>
  <body></body>
</html>

@metonym metonym merged commit bf2ee4c into master Nov 25, 2020
@metonym metonym deleted the feature-content-attr branch November 25, 2020 18:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant