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; }); };