请教 HtmlWebpackPlugin 通过 template 生成 html,导致 js css 文件重复

2022-04-06 21:48:20 +08:00
 matthewzhong

一个小的静态网站,目录结构就是 src-->dist 。

问一个 webpack 打包的问题。

  new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: "index.html",
            chunks: ['index']
        }),

导致打包后的 index.html 中的 js 跟 css 重复。如下:

 <!-- 原先模板自带 -->
   <link rel="stylesheet" href="index.css">
   <script src="index.js" defer="defer"></script>
   <script src="a.js" defer="defer"></script>
   <script src="b.js" defer="defer"></script>
   <!-- 构建后 inject -->
   <script defer="defer" src="index_755034f5329d7ad50060.js"></script>
   <link href="index_204d96044f9df227c786.css" rel="stylesheet">

有没有办法在构建时把原先模板中的 script,linkcss 标签移除。

貌似很早以前也有人问同样的问题,但没看到解决方案:

https://github.com/jantimon/html-webpack-plugin/issues/285

目前解决的方法就是,额外创建一个移除 script,linkcss 标签的模板 index_template.html

请问,有没有更简单更优雅的方法?

812 次点击
所在节点    问与答
6 条回复
noe132
2022-04-06 21:59:28 +08:00
那问题来了,为什么不能把原来的模板改一下?
matthewzhong
2022-04-06 22:02:11 +08:00
@noe132 加环境判断吗? webpack 不是很熟,能给个简单的示例吗?
DrakeXiang
2022-04-07 11:40:51 +08:00
为什么不能删掉 script/css ?
Envov
2022-04-07 12:16:35 +08:00
https://github.com/jantimon/html-webpack-plugin#configuration
使用 templateContent 根据实际情况动态创建 html 内容,不用 template
matthewzhong
2022-04-07 17:12:17 +08:00
@DrakeXiang 是啊,我就是问为什么不能自动删除? inject 比较容易理解和实现。但对于删除,可能不知道那些是需要删除,哪些是需要保留的。

> The easiest way is to use the template option and pass a custom HTML file. The html-webpack-plugin will automatically inject all necessary CSS, JS, manifest and favicon files into the markup.


@Envov 我目前也是额外创建一个移除 script,linkcss 标签的 html 模板,其实就是 templateContent 文件式的实现。所以,目前都要有一个 index.html 的模板副本,也无伤大雅。
DrakeXiang
2022-04-07 19:29:39 +08:00
我是问为什么你的模板不能删掉 script/css 。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/845345

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX