Skip to content

Object keys must be in alphabetical order #5

@cossssmin

Description

@cossssmin

Keys that you pass in the object to posthtml-content need to be in alphabetical order, otherwise replacements whose keys are in the wrong place (after the wrong letter) will not work.

For example this works:

require('posthtml-content')({
  a: str => str.replace(/foo/g, 'foo bar A'),
  z: str => str.replace(/foo/g, 'foo bar Z'),
})
<div z>Here's some foo</div>
<div a>Here's some foo</div>

Result:

<div>Here's some foo bar Z</div>
<div>Here's some foo bar A</div>

But if you pass the object like this:

require('posthtml-content')({
  z: str => str.replace(/foo/g, 'foo bar Z'),
  a: str => str.replace(/foo/g, 'foo bar A'),
})

Result:

<div>Here's some foo bar Z</div>
<div a>Here's some foo</div> <!-- this is not parsed -->

I suppose it has to do with the way intersectKeys.js works...

Temporary solution

For those bumping into this, until it's fixed, you can sort your object keys:

const posthtml = require('posthtml')
const posthtmlContent = require('posthtml-content')

// HTML
const html = `
  <div z>Here's some foo</div>
  <div a>Here's some foo</div>
`

// replacement keys in any order, maybe user defined?
let replacements = {
  z: str => str.replace(/foo/g, 'foo bar Z'),
  a: str => str.replace(/foo/g, 'foo bar A'),
}

replacements = Object.keys(replacements)
    .sort()
    .reduce((acc, key) => ({
      ...acc, [key]: replacements[key]
    }), {})

html = posthtml([posthtmlContent(replacements)]).process(html).then(res => res.html)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions