npm i -D html-loader posthtml-loader
The posthtml loader must be used with at least one other loader in order to integrate with webpack correctly. For most use cases, the html-loader is recommended. If you want to export the html string directly for use in javascript or webpack plugins, we recommend the source-loader. Whichever loader you choose, it should be the first loader, followed by posthtml, as you will see in the examples below.
Options can be passed through a posthtml
option directly on the webpack config object. It accepts an array, an object, or a function that returns an array or object. If it's an array, it should contain plugins. If it's an object, it can contain a plugins
key, which is an array of plugins and an optional parser
key which allows you to pass in a custom parser. Any other key will apply to the pack
querystring parameter, documented below.
Basic configuration example:
// webpack.config.js
module: {
loaders: [{
test: /\.html$/,
loader: 'html!posthtml'
}]
},
posthtml: [/* plugins here */]
If you need to apply different sets of plugins to different groups of files, you can use a plugin pack. Just add pack=[name]
as a querystring option, and return an object from the posthtml
config option with a key matching the pack name, and the value being an array of plugins.
// webpack.config.js
module: {
loaders: [{
test: /\\.special\.html$/,
loader: 'html!posthtml?pack=special'
}]
},
posthtml: {
plugins: [/* plugins that apply anything that's not using a pack */],
special: [ /* plugins specific to the "special" pack */ ],
}
If you want to use a custom parser, you can pass it in under the parser
key or as query string in the loader. Below is an example with the sugarml parser:
// webpack.config.js
const sugarml = require('sugarml')
module: {
loaders: [{
test: /\\.special\.html$/,
loader: 'html!posthtml'
}]
},
posthtml: {
plugins: [/* posthtml plugins */],
parser: sugarml
}
// webpack.config.js
const sugarml = require('sugarml')
module: {
loaders: [{
test: /\\.special\.html$/,
loader: 'html!posthtml?parser=sugarml'
}]
},
posthtml: {
plugins: [/* posthtml plugins */]
}
You can also return a function from the posthtml
config value, if you need to for any reason. The function passes along the loader context as an argument, so you can get information about the file currently being processed from this and pass it to plugins if needed. For example:
// webpack.config.js
module: {
loaders: [{
test: /\.html$/,
loader: 'html!posthtml'
}]
},
posthtml: (ctx) => {
return [ plugin({ filename: ctx.resourcePath })]
}
Michael Ciniawsky |
Jeff Escalante |
Ivan Demidov |
See PostHTML Guidelines and CONTRIBUTING.