0.16.6 • Published 6 months ago

posthtml v0.16.6

Weekly downloads
758,353
License
MIT
Repository
github
Last release
6 months ago

NPM 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.

Maintainers

Contributors

Backers

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

@parcel-nightly-unofficial/optimizer-htmlnano@parcel-nightly-unofficial/packager-html@parcel-nightly-unofficial/transformer-html@parcel-nightly-unofficial/transformer-posthtmlproject-name-here@ianlucas/parcel-bundlerswarm-websitetzar-core@eb3n/posthtml-components@eztool/prettier-plugin-formatter@ephesus/ephesus-coreposthtml-partposthtml-partialbuildgem-md2htmlalinesno-do-vueposthtml-fragmentposthtml-browser@twigger/posthtml@sdf-1/posthtml@everything-registry/sub-chunk-2463snowpack-plugin-posthtmles-module-traversales5-validator-plusember-applyemail-boilerlatesr-require-packsticky-scroll-catchenb-faviconsst-require-packempjsesbuild-plugin-html-minifycy-parcel@darekkay/11ty@divriots/legacy-jampackslidownelement-toolboxeleventy-plugin-automatic-noopenereleventy-plugin-helmeteleventy-plugin-json-feedeleventy-plugin-killer-filterselectron-posthtmlcreate-vite-pwa@danmarshall/parcel-bundlerdl-csscam-bakercataclysmcatalog-view@cabin-icarus/webpack-panoramaxcim-codesandbox@compiled/parcel-optimizer@coco-platform/critical@contentful/contentful-extension-scripts@coyote-labs/ember-fingerprint-assets@bundless/clichain_digger@designsystemsinternational/email@devorso/dcountdown@deja-vu/cli@dkwasniewski/paczka@demon673/webpack-panoramabemarkfigmakeflexscss-parcel-bundlerstyled-vuesuntmollitiafe-easy-packextract-sfc-blocksextract-sfc-tags@funish/bundleskeleton-posthtml@siteone/serve-statictailwind-to-styledt3-buildfis3-postprocessor-posthtml-beautifysvg-clrz-loaderexpress-posthtmlsvg-fill-loadersveltemodsvg-to-vue-componentfreelancefront3zeev-mailzeev-runwebpack-plugin-inject-externalwebpack-plugin-network-hintswebpack-panoramawebpack-panorama-xwebsite-dependency-graphwebpack4-cdn-pluginwebpack-upload-cdn-pluginwebtampkigokwasniew-parcel-bundlergemstone-loader-cssgemstone-loader-htmlultron-toolhapi-posthtmlvformlmqhash-staticvue-cli-plugin-eliar
0.16.7-beta.0

6 months ago

0.16.7-0

6 months ago

0.16.6

2 years ago

0.16.5

3 years ago

0.16.3

3 years ago

0.16.4

3 years ago

0.16.0

3 years ago

0.16.1

3 years ago

0.16.2

3 years ago

0.15.2

3 years ago

0.15.1

3 years ago

0.15.0

3 years ago

0.14.0

3 years ago

0.13.4

4 years ago

0.13.3

4 years ago

0.13.2

4 years ago

0.13.1

4 years ago

0.13.0

4 years ago

0.12.3

4 years ago

0.12.2

4 years ago

0.12.1

4 years ago

0.12.0

5 years ago

0.11.6

5 years ago

0.11.5

5 years ago

0.11.4

5 years ago

0.11.3

6 years ago

0.11.2

6 years ago

0.11.1

6 years ago

0.11.0

6 years ago

0.10.1

6 years ago

0.10.0

6 years ago

0.9.2

7 years ago

0.9.1

8 years ago

0.9.0

8 years ago

0.8.7

8 years ago

0.8.6

8 years ago

0.8.5

8 years ago

0.8.4

8 years ago

0.8.3

8 years ago

0.8.2

8 years ago

0.8.1

8 years ago

0.8.0

8 years ago

0.7.0

9 years ago

0.6.0

9 years ago

0.5.0

9 years ago

0.4.1

9 years ago

0.4.0

9 years ago

0.3.0

9 years ago

0.2.1

9 years ago

0.2.0

9 years ago

0.1.0

9 years ago

0.0.4

9 years ago

0.0.3

9 years ago

0.0.2

9 years ago

0.0.1

9 years ago