需要将引入js文件直接嵌入到html文件中,以减少文件的请求次数,达到更好的性能,htmlWebpackPlugin官方没有提供配置想去完成这个功能,但是由于该需求的广泛,官方提供了处理方法
https://github.com/jantimon/html-webpack-plugin/blob/master/examples/inline/template.jade
html对应的具体代码为:
<script>
<%for(varfileinhtmlWebpackPlugin.files.chunks){%>
<%=
compilation.assets[htmlWebpackPlugin.files.chunks[file].entry.substr(htmlWebpackPlugin.files.publicPath.length)].source()
%>
<%}%>
</script>
将这一段代码插入到你需要提升性能的html文件的head中,我这里简单写一个HTML文件
<!doctype html>
<html>
<head>
<title><%= htmlWebpackPlugin.options.title%></title>
<script>
<%for(var file in htmlWebpackPlugin.files.chunks){ %>
<%=
compilation.assets[htmlWebpackPlugin.files.chunks[file].entry.substr(htmlWebpackPlugin.files.publicPath.length)].source()
%>
<%}%>
</script>
</head>
<body>
<!--我是一行注释-->
</body>
</html>
思路就是在html先准备一个script标签,然后还是通过<%%>模板遍历配置文件中的chunks,取到对应的js文件的相对路径,通过compilation.assets['相对路径'].source()获取文件的内容,下面是webpack打包之后的html文件的内容,成功将js文件获取并嵌入到html文件中:
<!doctype html>
<html>
<head>
<title>index.html</title>
<script>
/