html-replace-webpack-plugin
A Webpack plugin for replace HTML contents with custom pattern string or regex.
Examples
https://github.com/iminif/html-replace-webpack-plugin-howto
💚 Special Note! 👀
This plugin works together with html-webpack-plugin!
Usage
First of all, you need both html-webpack-plugin
and html-replace-webpack-plugin
.
npm i -D html-webpack-plugin html-replace-webpack-plugin
Then, add it to your webpack.config.js
file:
webpack.config.js
file:
In your 💚 Please ensure that
html-webpack-plugin
was placed beforehtml-replace-webpack-plugin
in your Webpack config if you were working with Webpack 4.x!
var webpack = var HtmlReplaceWebpackPlugin = // file types & file linksconst resource = js: bootstrap: '//cdn/bootstrap/bootstrap.min.js' css: bootstrap: '//cdn/bootstrap/bootstrap.min.css' img: 'the-girl': '//cdn/img/the-girl.jpg' const tpl = img: '<img src="%s">' css: '<link rel="stylesheet" type="text/css" href="%s">' js: '<script type="text/javascript" src="%s"></script>' moduleexports = // Definition for Webpack plugins plugin: /* configs */ // Replace html contents with string or regex patterns pattern: 'foo' replacement: '`foo` has been replaced with `bar`' pattern: '@@title' replacement: 'html replace webpack plugin' pattern: /<p><\/p>/g // /g => replace all replacement: '<div>$1</div>' pattern: /:?/g { // those formal parameters could be: // match: <-- css:bootstrap--> // type: css // file: bootstrap // Then fetch css link from some resource object // var url = resources['css']['bootstrap'] var url = resourcetypefile // $1==='@@' <--EQ--> $4===undefined return $4 == undefined ? url : tpltype }
src/index.html
file:
In your @@title <!-- css:bootstrap --> foo I wanna be in a div <!-- js:bootstrap -->
dist/index.html
file:
After replacing, in the html replace webpack plugin `foo` has been replaced with `bar` I wanna be in a div
API
html-replace-webpack-plugin can be called with an objects array or an object.
html-replace-webpack-plugin
Options for new HtmlReplaceWebpackPlugin([obj1[, obj2[, obj3[, ...[, objN]]]]] | obj)
[obj1[, obj2[, obj3[, ...[, objN]]]]] | obj
Type: Objects Array
| Object
obj1, obj2, obj3, ..., objN | obj
Type: Object
obj.pattern
Type: String
| RegExp
string or regex pattern for matching HTML content. See the MDN documentation for RegExp for details.
obj.replacement
Type: String
| Function
string with which the matching string be replaced, or function which returns a string for replacing. See the MDN documentation for String.replace for details.