html-webpack-plugin在html中插入數據
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> </body> </html>
查看文檔,有如下介紹:
可以使用lodash語法在模板中注入數據。
下面的變量在模板中可以使用:
- htmlWebpackPlugin.options: 通過
new htmlWebpackPlugin(options)
傳遞. - webpack: 通過
compilation.getStats().toJson()
得到的一個對象. - webpackConfig對象: 比如
webpackConfig.output.publicPath
獲取webpack.prod.conf.js
中的publicPath compilation
對象.htmlWebpackPlugin.files
: 格式如下
"htmlWebpackPlugin": { "files": { "css": [ "main.css" ], "js": [ "https://www.baidu.com/static/js/app.cfebce17280ae88b6b7b.js"], "chunks": {} } }
如何實現的呢?
主要在emit階段,通過如下方法實現(/node_modules/html-webpack-plugin/index.js):
HtmlWebpackPlugin.prototype.executeTemplate = function (templateFunction, chunks, assets, compilation) { var self = this; return Promise.resolve() // Template processing .then(function () { var templateParams = { compilation: compilation, webpack: compilation.getStats().toJson(), webpackConfig: compilation.options, htmlWebpackPlugin: { files: assets, options: self.options } }; var html = ''; try { html = templateFunction(templateParams);// 注入到模板方法中 } catch (e) {...} return html; }); };