Discover the Power of posthtml with Comprehensive API Examples for SEO Optimization

Introduction to PostHTML

PostHTML is a transformative toolkit for processing HTML with JavaScript plugins. It provides an easy way to modify and extend HTML with plugins, making it a valuable tool for web developers looking to optimize their workflows and improve SEO.

API Examples

Basic Usage


const posthtml = require('posthtml');
const plugin = (tree) => {
  tree.match({ tag: 'div' }, (node) => {
    node.tag = 'section';
    return node;
  });
};

posthtml([ plugin ])
  .process('
Hello World
') .then((result) => console.log(result.html));

This example demonstrates the basic setup of PostHTML. The plugin changes all <div> tags to <section> tags.

Using PostHTML with Plugins


const posthtml = require('posthtml');
const expressions = require('posthtml-expressions');

posthtml([ expressions({ locals: { foo: 'bar' } }) ])
  .process('
Hello World
') .then((result) => console.log(result.html));

In this example, the posthtml-expressions plugin is used to conditionally render HTML based on local variables.

Transforming Attributes


const posthtml = require('posthtml');
const plugin = (tree) => {
  tree.match({ tag: 'img' }, (node) => {
    node.attrs = node.attrs || {};
    node.attrs.alt = 'Image description';
    return node;
  });
};

posthtml([ plugin ])
  .process('')
  .then((result) => console.log(result.html));

This plugin automatically adds an alt attribute to all <img> tags for better SEO.

App Example

Here’s a simple application that utilizes the discussed APIs to enhance HTML with several plugins.


const posthtml = require('posthtml');
const expressions = require('posthtml-expressions');
const beautify = require('posthtml-beautify');

const plugins = [
  expressions({ locals: { foo: 'bar' } }),
  tree => tree.match({ tag: 'div' }, (node) => {
    node.tag = 'section';
    return node;
  }),
  tree => tree.match({ tag: 'img' }, (node) => {
    node.attrs = node.attrs || {};
    node.attrs.alt = 'Image description';
    return node;
  }),
  beautify({ rules: { indent: 2 } })
];

const html = `
Hello World!
`; posthtml(plugins) .process(html) .then(result => console.log(result.html));

This complete example demonstrates the use of multiple PostHTML plugins to transform a sample HTML string. It conditionally renders a section, adds an alt attribute to an image, and beautifies the final output for better readability.

Hash: 8b6d9bae724c9113a9f8311ca6d2b24364d2edda528ad2c6e5e291bb14214bc3

Leave a Reply

Your email address will not be published. Required fields are marked *