This PostHTML plugin allows you to programmatically rename HTML attributes through a custom function.
npm i -D posthtml posthtml-rename-attrs
You simply define a function that returns the renamed attribute.
For example, let's rename all src
attributes:
const posthtml = require('posthtml');
const renameAttrs = require('posthtml-rename-attrs');
// If the attribute is 'class', rename it
const prefix = (v) => v === 'src' ? `data-${v}` : v;
posthtml([renameAtrs(prefix)])
.process('<img src="...">')
.then(function(result) {
console.log(result);
});
Result:
<img data-src="...">