/posthtml

PostHTML is a tool to transform HTML/XML with JS plugins. By http://theprotein.io team.

Primary LanguageJavaScript

npm Build Coverage Chat

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

Usage

npm i -D posthtml

API

Simple example

const posthtml = require('posthtml');

let html = `
    <myComponent>
      <myTitle>Super Title</myTitle>
      <myText>Awesome Text</myText>
    </myComponent>`;

posthtml()
    .use(require('posthtml-custom-elements')())
    .process(html/*, options */)
    .then(function(result) {
        console.log(result.html);
        // <div class="myComponent">
        //  <div class="myTitle">Super Title</div>
        //  <div class="myText">Awesome Text</div>
        // </div>
    });

Сomplex example

const posthtml = require('posthtml');

let 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(function(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>
    });

CLI

Install posthtml-cli

npm i posthtml-cli
posthtml -o output.html -i input.html -c config.json

or

"scripts": {
  "html": "echo '=> Building HTML' && posthtml -o output.html -i input.html -c config.json"
}
npm run html

Gulp

Install gulp-posthtml

npm i -D gulp-posthtml
gulp.task('html', function() {
    let posthtml = require('gulp-posthtml');
    return gulp.src('src/**/*.html')
        .pipe(posthtml([ require('posthtml-custom-elements')() ]/*, options */))
        .pipe(gulp.dest('build/'));
});

Check project-stub example with Gulp

Grunt

Install grunt-posthtml

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

Webpack

Install posthtml-loader

npm i -D posthtml-loader
const bem = require('posthtml-bem')()
const each = require('posthtml-each')()

module.exports = {
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'html!posthtml'
      }
    ]
  }
  posthtml: function () {
    return {
      defaults: [ bem, each ]
    }
  }
}

with custom package

const bem = require('posthtml-bem')()
const each = require('posthtml-each')()
const include = require('posthtml-include')()

module.exports = {
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'html!posthtml?pack=html'
      }
    ]
  }
  posthtml: function () {
    return {
      defaults: [ bem, each ],
      html: [ bem, each, include ]
    }
  }
}

PostHTML with Jade engine in Express

Also it's work with other view engine. Callback in app.engine is called by res.render() to render the template code.

app.engine('jade', function (path, options, callback) {
    // PostHTML plugins
    let plugins = [
        require('posthtml-bem')(),
        require('posthtml-textr')({ locale: 'ru'}, [
            require('typographic-ellipses'),
            require('typographic-single-spaces'),
            require('typographic-quotes')
        ])
    ];

    let html = require('jade').renderFile(path, options);

    posthtml(plugins)
        .process(html)
        .then(function (result) {
            if (typeof callback === 'function') {
                var res;
                try {
                    res = result.html;
                } catch (ex) {
                    return callback(ex);
                }
                return callback(null, res);
            }
        });
})
app.set('view engine', 'jade');

Middleware

Koa

koa-posthtml

Hapi

hapi-posthtml

Express

express-posthtml

Electron

electron-posthtml

Plugins

Take a look at the searchable Plugins Catalog for PostHTML plugins.

Plugin Status                  Description
posthtml-bem npm Support BEM naming in html structure
posthtml-postcss npm Use PostCSS in HTML document
posthtml-retext npm Extensible system for analysing and manipulating natural language
posthtml-custom-elements npm Use custom elements now
posthtml-web-component [npm][web-2] Web Component ServerSide Rending, Component as Service in Server
posthtml-inline-css npm CSS Inliner
posthtml-style-to-file npm Save HTML style nodes and attributes to CSS file
posthtml-px2rem npm Change px to rem in HTML inline CSS
posthtml-classes npm Get a list of classes from HTML
posthtml-doctype npm Extend html tags doctype
posthtml-include npm Include html file
posthtml-to-svg-tags npm Convert html tags to svg equals
posthtml-extend-attrs npm Extend html tags attributes with custom data and attributes
posthtml-modular-css npm Makes css modular
posthtml-static-react npm Render custom elements as static React components
posthtml-head-elements npm Store head elements (title, script, link, base and meta) in a JSON file and render them into the document during the build process
posthtml-prefix-class npm Prefix class names
posthtml-collect-inline-styles npm Collect inline styles and insert to head tag
posthtml-transformer npm process HTML by directives in node attrs, such as inline scripts and styles, remove useless tags, concat scripts and styles etc.
posthtml-inline-assets npm Inline external scripts, styles, and images in HTML
posthtml-schemas npm Add schema.org microdata to your markup super easy
posthtml-extend npm Templates extending (Jade-like)
posthtml-img-autosize npm Auto setting the width and height of <img>
posthtml-aria-tabs npm Write accessible tabs with minimal markup
posthtml-lorem npm Add lorem ipsum placeholder text to any document
posthtml-md npm Easily use context-sensitive markdown within HTML
posthtml-alt-always npm Always add alt attribute for images that don't have it (accessibility reasons)
posthtml-css-modules npm Use CSS modules in HTML
posthtml-jade npm Jade templates/syntax support
posthtml-exp npm Add template expressions to your HTML
posthtml-tidy npm Sanitize HTML with HTML Tidy on the fly
posthtml-hint npm Lint HTML with HTML Hint
posthtml-w3c npm Validate HTML with W3C Validation
posthtml-load-plugins npm Auto-load Plugins for PostHTML

License

MIT

[web-2]: https://badge.fury.io/js/posthtml-web-components)