A flexible and powerful HTML transformation library that allows you to apply rules to HTML content using CSS selectors.
- Transform HTML content from various input types (string, Buffer, Readable stream, or Cheerio API)
- Apply multiple transformation rules in sequence
- Use any valid CSS selector supported by Cheerio (including complex pseudo-selectors)
- Support for asynchronous transformation rules
- Modify content, attributes, structure, and more
- Transform elements in both
<head>and<body>sections
npm install @packt/html-transformerimport{Transformer,TranformationRule}from'@packt/html-transformer';// Define transformation rulesconstrules: TranformationRule[]=[{selector: ['h1'],// Target all h1 elementsrule: async(node,$)=>{node.addClass('title');node.text(`Modified: ${node.text()}`);}},{selector: ['a'],// Target all linksrule: async(node,$)=>{consthref=node.attr('href');if(href&&!href.startsWith('https://')){node.attr('href',`https://example.com${href}`);}}}];// Create transformerconsttransformer=newTransformer(rules);// Transform HTML stringconsthtml='<html><body><h1>Original Title</h1><a href="/link">Link</a></body></html>';constresult=awaittransformer.transform(html);console.log(result);// Outputs: HTML with modified title and linkThe transformer accepts various input types:
// String inputconsthtmlString='<div>Hello world</div>';constresult1=awaittransformer.transform(htmlString);// Buffer inputconstbuffer=Buffer.from('<div>Hello world</div>');constresult2=awaittransformer.transform(buffer);// Stream inputconststream=Readable.from(['<div>Hello',' world</div>']);constresult3=awaittransformer.transform(stream);// Cheerio API inputconst$=cheerio.load('<div>Hello world</div>');awaittransformer.transform($);constresult4=$.html();The library supports all CSS selectors available in Cheerio:
construles: TranformationRule[]=[{// Target divs that contain spansselector: ['div:has(span)'],rule: async(node,$)=>{node.addClass('has-span');}},{// Target the second item in listsselector: ['li:nth-child(2)'],rule: async(node,$)=>{node.addClass('second-item');}},{// Target paragraphs that don't have a specific classselector: ['p:not(.exclude)'],rule: async(node,$)=>{node.addClass('included');}},{// Target multiple selectors in one ruleselector: ['h1','h2','h3'],rule: async(node,$)=>{node.addClass('heading');}}];You can also target and modify elements in the <head> section:
construles: TranformationRule[]=[{selector: ['title'],rule: async(node,$)=>{node.text('New Page Title');}},{selector: ['meta[name="description"]'],rule: async(node,$)=>{node.attr('content','Updated description for SEO');}},{selector: ['head'],rule: async(node,$)=>{// Add a new meta tagnode.append('<meta name="robots" content="noindex">');}}];{selector: ['.target'],rule: async(node,$)=>{node.addClass('new-class');}}{selector: ['img'],rule: async(node,$)=>{node.attr('alt','Descriptive alt text');node.attr('loading','lazy');}}{selector: ['table'],rule: async(node,$)=>{node.wrap('<div class="table-responsive"></div>');}}{selector: ['p'],rule: async(node,$)=>{consttext=node.text();node.html(`<strong>${text}</strong>`);}}The rule function provides access to the Cheerio API, allowing for more complex manipulations:
{selector: ['article'],rule: async(node,$)=>{// Find all images without alt text within this articleconstimages=node.find('img:not([alt])');images.each((i,img)=>{$(img).attr('alt','Article image');});// Add a class to all paragraphs within this articlenode.find('p').addClass('article-text');}}The main class for transforming HTML.
constructor(rules: TranformationRule[])Creates a new Transformer instance with the specified rules.
asynctransform($: CheerioAPI): Promise<void>;asynctransform(html: string): Promise<string>;asynctransform(html: Buffer): Promise<string>;asynctransform(html: Readable): Promise<string>;Transforms the input HTML according to the rules.
interfaceTranformationRule{selector: string[];// Array of CSS selectorsrule: (node: Cheerio<AnyNode>,$: CheerioAPI)=>Promise<void>;}selector: An array of CSS selectors that determine which elements the rule will be applied torule: An async function that receives the matched element and the Cheerio API instance
MIT