Giter Site home page Giter Site logo

posthtml / posthtml Goto Github PK

View Code? Open in Web Editor NEW
2.9K 50.0 114.0 1.11 MB

PostHTML is a tool to transform HTML/XML with JS plugins

Home Page: https://posthtml.org

License: MIT License

JavaScript 91.80% HTML 7.57% Shell 0.62%
posthtml parser html xml xml-parser html-parser transformer

posthtml's Introduction

NPM Tests Coverage Standard Code Style

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

Name Status Description
posthtml-parser npm Parser HTML/XML to PostHTMLTree
posthtml-render npm Render 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>

⚠️ 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>
npm i posthtml-cli
"scripts": {
  "posthtml": "posthtml -o output.html -i input.html -c config.json"
}
npm run posthtml
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

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,
      }
    ]
  }
}
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
$ 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)
Name Status Description
posthtml-pug npm Pug Parser
sugarml npm SugarML Parser

Plugins

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

Maintainers


Ivan Demidov

Ivan Voischev

Contributors

Backers

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

posthtml's People

Contributors

a avatar awinogradov avatar caseywebb avatar chimurai avatar cossssmin avatar cronfy avatar dependabot[bot] avatar gitter-badger avatar greenkeeperio-bot avatar island205 avatar maltsev avatar metonym avatar michael-ciniawsky avatar mohsen1 avatar monkeywithacupcake avatar mrmlnc avatar panstav avatar phloe avatar qfox avatar rajdee avatar scrum avatar shvaikalesh avatar shyam-chen avatar simonlc avatar stevenbenisek avatar sukkaw avatar tcotton avatar voischev avatar vovanr avatar vtrrsl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

posthtml's Issues

A few parsing issues

I've notice a few errors with the below code while parsing through postHTML..

In this example only one of the div's get output into the tree:

<div class="wow">
    one
</div>
<div class="wow">
    two
</div>

In this example only the class attribute is being recognised

<div class="wow" id="IDs-dont-get-recognised" role="test" data-test="hello" doiexist="umm">
    two
</div>

Is this a bug, features yet to be implemented or by design?

Cheers :)

Own converter html

html2bemjson not right convert this

<!DOCTYPE html>
<html><head><title>Test</title></head><body><div class="button"><div class="button__text">Text</div></div></body></html>

doctype is empty!

About PostHTML

81515c5

Write some text about posthtml. Ex: posthtml can be used for add or clean html attrs, update classes, simplify structures and etc. More more and more about it. Aslo you can write about the similarity with postcss in ideas.

Chaining?

tree.match([{ tag: 'head' }, { tag: 'iframe' }], () => '');
tree.match({ tag: 'body' }, node => {
    node.tag = false;
    return node;
});

VS

tree
    .match([{ tag: 'head' }, { tag: 'iframe' }], () => '')
    .match({ tag: 'body' }, node => {
        node.tag = 'div';
        return node;
    });

[feat]: Separate render module

posthtml-renderer

Motivation is possibility to generation special markup in non standard situations. Custom renderer should add method with self name, ex: posthtml().process(String).svg()

API

Suggest to add .each(selector, callback) method. It's the most usable thing to transform html.

Don't generate HTML by default

Posthtml generate HTML now after processing a string with markup. In special situations this functionality isn't required. If you want to get tree only HTML generation decrease your performance.

How to: html is method of posthtml-tree instead of attribute. Ex: posthtml().process(String).html().

how to save existen formatting?

Current implementation removed spaces (wich is not expected).
Is it possible to save existen formatting (spaces, etc)? maybe some option?

Plugin idea: currency

Hi!
I think would be cool to replace somehow unsupported (yet) (in older OS/browsers) currency glyphs with some fallback.
For example:
₽ – Russian ruble
Can be replaced to <span class="ruble">c</span> to use “ALS Rubl” font where letters are following style of some other fonts, c is for Arial Bold.
Can be replaced to <span class="ruble-arial-bold">руб.</span> to use pseudo-element with content: "c";.
Or I have just to use basic text replacement?

walk() and match() as a separate module

Sometimes I need to find a node in a tree, which hasn't walk() and match() functions (subtree, for example). What do you think, if we decouple these functions in a separate module (like posthtml-parser and posthtml-render)? So they can be used everywhere, with all kinds of PostHTML-trees.

posthtml hanging, potentially while walking a tree?

Hey there,

We're exploring converting our many HTML plugins to the PostHTML ecosystem. While converting one of them, we found that a simple change is causing the process to hang.

https://github.com/Rebelmail/html-uglify/tree/posthtml

Running the tests with npm test in that branch will expose the bug.

Changing this line https://github.com/Rebelmail/html-uglify/blob/posthtml/lib/main.js#L106 to something like node.attrs[type] = 'XXX' seems to make the hang go away.

My gut reaction is that this has to do with posthtml getting confused since we're modifying attributes. Any ideas? (Because we're stuck.)

Parent/child nodes

Is it possible to get list of parent or child nodes? Or walk trough child or parent nodes?

Add sync method for result compile

Async

posthtml()
    .use(plugin)
    .process(html/*, options */)
    .then(function(result) {
        // result.html
        // result.tree
    });

Sync

var newHtml = posthtml()
    .use(plugin)
    .process(html/*, options */)
    .html; // or .tree

deep result objects

Хочется получать более богатый результат.
Например

posthtml()
    .process(tree, { skipParse : true })
    .then(result => {
        result.html 
        result.tree
        result.getOptions() 
    })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.