Skip to content

awsr/posthtml-retag

Repository files navigation

PostHTML-Retag

NPM

A PostHTML plugin for converting HTML tags to a specified target type.

Useful as part of a post-export script for visual editors that don't support certain tags, among other things.

(NOTE: As of version 2.0.0 retag is a named export/import instead of a default one and is targeted/tested on Node 16+.)

Before:

<html>
  <body>
    <!-- ... content -->
    <div retag="noscript">
      <div>
        <span>Noscript content</span>
      </div>
    </div>
    <div retag="template">
      <span>Some more content</span>
    </div>
  </body>
</html>

After:

<html>
  <body>
    <!-- ... content -->
    <noscript>
      <div>
        <span>Noscript content</span>
      </div>
    </noscript>
    <template>
      <span>Some more content</span>
    </template>
  </body>
</html>

Install

npm install --save-dev posthtml posthtml-retag

Usage

ES Module format
import { readFileSync, writeFileSync } from 'node:fs';
import posthtml from 'posthtml';
import { retag } from 'posthtml-retag';
// Import additional plugins (if any)

const html = readFileSync('/path/to/input.html', 'utf8');

posthtml(
  [
    retag({
      attr: 'retag',
      removeDisplayNone: false
    }),
    // Additional plugins
  ])
  .process(html)
  .then(result => writeFileSync('/path/to/output.html', result.html));
CommonJS format
const { readFileSync, writeFileSync } = require('node:fs');
const posthtml = require('posthtml');
const { retag } = require('posthtml-retag');
// Import additional plugins (if any)

const html = readFileSync('/path/to/input.html', 'utf8');

posthtml(
  [
    retag({
      attr: 'retag',
      removeDisplayNone: false
    }),
    // Additional plugins
  ])
  .process(html)
  .then(result => writeFileSync('/path/to/output.html', result.html));

Options

attr

Type: string

Default: retag

Specify the attribute that stores the name of the tag you want to convert to.

removeDisplayNone

Type: boolean

Default: false

Set to true to also remove display: none; from the style attribute of the element being converted unless it's set as !important. If it's the only value in the style attribute, the style attribute will be removed.

<div retag="template" style="display: none">stuff</div>
<div retag="template" style="display: none !important">stuff</div>
<template>stuff</template>
<template style="display: none !important">stuff</template>