Socket
Socket
Sign inDemoInstall

posthtml

Package Overview
Dependencies
8
Maintainers
2
Versions
55
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    posthtml

HTML/XML processor


Version published
Maintainers
2
Created

Changelog

Source

<small>0.15.2 (2021-04-13)</small>

  • 0.15.2 (64a1aeb)
  • build: update dependencies (a7a5d59)
  • build(deps): bump ini from 1.3.5 to 1.3.8 (919a412)
  • build(deps): bump y18n from 4.0.0 to 4.0.1 (0d8d16e)
  • chore: update readme (d90f573)

Readme

Source

NPM Deps Tests Coverage Standard Code Style Twitter

PostHTML

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

All HTML transformations are made by plugins. And these plugins are just small plain JS functions, which receive a HTML node tree, transform it, and return a modified tree.

For more detailed information about PostHTML in general take a look at the docs.

Dependencies

NameStatusDescription
posthtml-parsernpmParser HTML/XML to PostHTMLTree
posthtml-rendernpmRender PostHTMLTree to HTML/XML

Create to your project

npm init posthtml

Install

npm i -D posthtml

Usage

API

Sync

import posthtml from 'posthtml'

const html = `
  <component>
    <title>Super Title</title>
    <text>Awesome Text</text>
  </component>
`

const result = posthtml()
  .use(require('posthtml-custom-elements')())
  .process(html, { sync: true })
  .html

console.log(result)
<div class="component">
  <div class="title">Super Title</div>
  <div class="text">Awesome Text</div>
</div>

:warning: Async Plugins can't be used in sync mode and will throw an Error. It's recommended to use PostHTML asynchronously whenever possible.

Async

import posthtml from 'posthtml'

const html = `
  <html>
    <body>
      <p class="wow">OMG</p>
    </body>
  </html>
`

posthtml(
  [
    require('posthtml-to-svg-tags')(),
    require('posthtml-extend-attrs')({
      attrsTree: {
        '.wow' : {
          id: 'wow_id',
          fill: '#4A83B4',
          'fill-rule': 'evenodd',
          'font-family': 'Verdana'
        }
      }
    })
  ])
  .process(html/*, options */)
  .then((result) =>  console.log(result.html))
<svg xmlns="http://www.w3.org/2000/svg">
  <text
    class="wow"
    id="wow_id"
    fill="#4A83B4"
    fill-rule="evenodd" font-family="Verdana">
      OMG
  </text>
</svg>

Directives

import posthtml from 'posthtml'

const php = `
  <component>
    <title><?php echo $title; ?></title>
    <text><?php echo $article; ?></text>
  </component>
`

const result = posthtml()
  .use(require('posthtml-custom-elements')())
  .process(html, {
    directives: [
      { name: '?php', start: '<', end: '>' }
    ]
  })
  .html

console.log(result)
<div class="component">
  <div class="title"><?php echo $title; ?></div>
  <div class="text"><?php echo $article; ?></div>
</div>

CLI

npm i posthtml-cli
"scripts": {
  "posthtml": "posthtml -o output.html -i input.html -c config.json"
}
npm run posthtml

Gulp

npm i -D gulp-posthtml
import tap from 'gulp-tap'
import posthtml from 'gulp-posthtml'
import { task, src, dest } from 'gulp'

task('html', () => {
  let path

  const plugins = [ require('posthtml-include')({ root: `${path}` }) ]
  const options = {}

  src('src/**/*.html')
    .pipe(tap((file) => path = file.path))
    .pipe(posthtml(plugins, options))
    .pipe(dest('build/'))
})

Check project-stub for an example with Gulp

Grunt

npm i -D grunt-posthtml
posthtml: {
  options: {
    use: [
      require('posthtml-doctype')({ doctype: 'HTML 5' }),
      require('posthtml-include')({ root: './', encoding: 'utf-8' })
    ]
  },
  build: {
    files: [
      {
        dot: true,
        cwd: 'html/',
        src: ['*.html'],
        dest: 'tmp/',
        expand: true,
      }
    ]
  }
}

Webpack

npm i -D html-loader posthtml-loader
v1.x

webpack.config.js

const config = {
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'html!posthtml'
      }
    ]
  },
  posthtml: (ctx) => ({
    parser: require('posthtml-pug'),
    plugins: [
      require('posthtml-bem')()
    ]
  })
}

export default config
v2.x

webpack.config.js

import { LoaderOptionsPlugin } from 'webpack'

const config = {
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
            options: { minimize: true }
          },
          {
            loader: 'posthtml-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new LoaderOptionsPlugin({
      options: {
        posthtml(ctx) {
          return {
            parser: require('posthtml-pug'),
            plugins: [
              require('posthtml-bem')()
            ]
          }
        }
      }
    })
  ]
}

export default config

Rollup

$ npm i rollup-plugin-posthtml -D
# or
$ npm i rollup-plugin-posthtml-template -D
import { join } from 'path';

import posthtml from 'rollup-plugin-posthtml-template';
// or
// import posthtml from 'rollup-plugin-posthtml';

import sugarml from 'posthtml-sugarml';  // npm i posthtml-sugarml -D
import include from 'posthtml-include';  // npm i posthtml-include -D

export default {
  entry: join(__dirname, 'main.js'),
  dest: join(__dirname, 'bundle.js'),
  format: 'iife',
  plugins: [
    posthtml({
      parser: sugarml(),
      plugins: [include()],
      template: true  // only rollup-plugin-posthtml-template
    })
  ]
};

Parser

import pug from 'posthtml-pug'

posthtml().process(html, { parser: pug(options) }).then((result) => result.html)
NameStatusDescription
posthtml-pugnpmPug Parser
sugarmlnpmSugarML Parser

Plugins

In case you want to develop your own plugin, we recommend using posthtml-plugin-starter to get started.

TEXT
NameStatusDescription
posthtml-mdnpmEasily use context-sensitive markdown within HTML
posthtml-tocnpmTable of contents
posthtml-loremnpmAdd lorem ipsum placeholder text to any document
posthtml-retextnpmExtensible system for analysing and manipulating natural language
prevent-widowsnpmPrevent widows from appearing at the end of paragraphs
posthtml-richtyponpmProcess HTML node text with Richtypo
HTML
NameStatusDescription
posthtml-doctypenpmSet !DOCTYPE
posthtml-head-elementsnpmInclude head elements from JSON file
posthtml-includenpmInclude HTML
posthtml-modulesnpmInclude and process HTML
posthtml-extendnpmExtend Layout (Pug-like)
posthtml-extend-attrsnpmExtend Attrs
posthtml-expressionsnpmTemplate Expressions
posthtml-inline-assetsnpmInline external scripts, styles, and images
posthtml-static-reactnpmRender custom elements as static React components
posthtml-custom-elementsnpmUse custom elements
posthtml-web-componentnpmWeb Component server-side rendering, Component as a Service (CaaS)
posthtml-spacelessnpmRemove whitespace between HTML tags
posthtml-cachenpmAdd a nanoid to links in your tags
posthtml-highlightnpmSyntax highlight code elements
posthtml-pseudonpmAdd pseudo selector class names to elements
posthtml-noopenernpmAdd rel="noopener noreferrer" to links that open in new tab
posthtml-noscriptnpmInsert noscript content when JavaScript is disabled
posthtml-hashnpmHash static CSS/JS assets
posthtml-insert-atnpmAppend/prepend HTML to a selector
posthtml-plugin-remove-duplicatesnpmRemove duplicated tags
posthtml-plugin-link-preloadnpmAdd preload/prefetch tags (or return equivalent headers)
posthtml-prismnpmCode syntax highlighting with Prism
posthtml-url-parametersnpmAdd parameters to URLs
posthtml-safe-class-namesnpmReplace escaped characters in class names and CSS selectors
posthtml-fetchnpmFetch and render remote content
posthtml-msonpmMakes it easy to write Outlook conditionals in HTML emails
posthtml-postcss-merge-longhandnpmMerge longhand inline CSS into shorthand
posthtml-markdownitnpmTransform Markdown using markdown-it
posthtml-extra-attributesnpmAdd new attributes to elements in your HTML
posthtml-srinpmAdds subresource integrity (SRI) attributes.
CSS
NameStatusDescription
posthtml-bemnpmSupport BEM naming in html structure
posthtml-postcssnpmUse PostCSS in HTML document
posthtml-px2remnpmChange px to rem in Inline CSS
posthtml-css-modulesnpmUse CSS modules in HTML
posthtml-postcss-modulesnpmCSS Modules in html
posthtml-classesnpmGet a list of classes from HTML
posthtml-prefix-classnpmPrefix class names
posthtml-modular-cssnpmMake CSS modular
posthtml-inline-cssnpmCSS Inliner
posthtml-collect-stylesnpmCollect styles from html and put it in the head
posthtml-collect-inline-stylesnpmCollect inline styles and insert to head tag
posthtml-style-expantionnpmPostHTML plugin expand link rel="stylesheet".
posthtml-style-to-filenpmSave HTML style nodes and attributes to CSS file
posthtml-color-shorthand-hex-to-six-digitnpmEnforce all hex color codes to be 6-char long
posthtml-minify-classnamesnpmRewrites classnames and ids inside of html and css files to reduce file size.
IMG & SVG
NameStatusDescription
posthtml-img-autosizenpmAuto setting the width and height of <img>
posthtml-to-svg-tagsnpmConvert html tags to svg equivalents
posthtml-webpnpmAdd WebP support for images
posthtml-faviconsnpmGenerate Favicons and add related tags
posthtml-inline-svgnpmInline svg icons in HTML
posthtml-inline-faviconnpmInline favicons in HTML
Accessibility
NameStatusDescription
posthtml-aria-tabsnpmWrite accessible tabs with minimal markup
posthtml-alt-alwaysnpmAlways add alt attribute for images that don't have it
posthtml-schemasnpmAdd microdata to your HTML
Optimization
NameStatusDescription
posthtml-shortennpmShorten URLs in HTML
posthtml-uglifynpmShorten CSS in HTML
posthtml-minifiernpmMinify HTML
posthtml-remove-attributesnpmRemove attributes unconditionally or with content match
posthtml-remove-tagsnpmRemove tags with content match
posthtml-remove-duplicatesnpmRemove duplicate elements from your html
posthtml-transformernpmProcess HTML by directives in node attrs, such as inline scripts and styles, remove useless tags, concat scripts and styles etc.
htmlnanonpmHTML Minifier
posthtml-link-noreferrernpmAdd rel="noopener" and rel="noreferrer" to all links that contain the attribute target="_blank"
posthtml-lazyloadnpmAdd native lazyload attribute
posthtml-postcss-treeshakernpmTree shake styles for classes and ids in style tag
posthtml-external-linknpmAdd rel="external noopenner nofollow" and target="_blank" to all external links
Workflow
NameStatusDescription
posthtml-load-pluginsnpmAutoload Plugins
posthtml-load-optionsnpmAutoload Options (Parser && Render)
posthtml-load-confignpmAutoload Config (Plugins && Options)
posthtml-w3cnpmValidate HTML with W3C Validation
posthtml-hintnpmLint HTML with HTML Hint
posthtml-tidynpmSanitize HTML with HTML Tidy

Middleware

NameStatusDescription
koa-posthtmlnpmKoa Middleware
hapi-posthtmlnpmHapi Plugin
express-posthtmlnpmExpress Middleware
electron-posthtmlnpmElectron Plugin
metalsmith-posthtmlnpmMetalsmith Plugin

Maintainers


Ivan Demidov

Ivan Voischev

Contributing

See PostHTML Guidelines and CONTRIBUTING.

Contributors

Backers

Thank you to all our backers! 🙏 [Become a backer]

LICENSE

MIT

Keywords

FAQs

Last updated on 13 Apr 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc