Skip to content

Instantly share code, notes, and snippets.

@jmblog
Last active October 5, 2021 06:05
Show Gist options
  • Save jmblog/15b0b51228851e17785ac1b69d60fabd to your computer and use it in GitHub Desktop.
Save jmblog/15b0b51228851e17785ac1b69d60fabd to your computer and use it in GitHub Desktop.
rehype plugin to remove all style attributes
import { Transformer } from 'unified';
import { Element } from 'hast';
import { visit } from 'unist-util-visit';
export default function rehypeRemoveStyleAttrs(): Transformer {
return (tree) => {
visit(tree, 'element', (node: Element) => {
if (node.properties?.style) {
node.properties.style = undefined;
}
});
};
}
@jmblog
Copy link
Author

jmblog commented Oct 5, 2021

Usage

import { unified } from 'unified';
import parse from 'rehype-parse';
import stringify from 'rehype-stringify';
import removeStyleAttrs from './rehype-remove-style-attrs';

const html = '<span style="color: #027cbb">aaa</span>';

const processor = unified()
  .use(parse, { fragment: true })
  .use(removeStyleAttrs)
  .use(stringify);

processor.processSync(html).value.toString(); // returns '<span>aaa</span>'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment