webpack将html引用的js文件直接嵌入到页面中以减少请求的次数

需要将引入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>
    
    /
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值