V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
matthewzhong
V2EX  ›  问与答

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

  •  
  •   matthewzhong · 2022-04-06 21:48:20 +08:00 · 788 次点击
    这是一个创建于 722 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一个小的静态网站,目录结构就是 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

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

    6 条回复    2022-04-07 19:29:39 +08:00
    noe132
        1
    noe132  
       2022-04-06 21:59:28 +08:00
    那问题来了,为什么不能把原来的模板改一下?
    matthewzhong
        2
    matthewzhong  
    OP
       2022-04-06 22:02:11 +08:00
    @noe132 加环境判断吗? webpack 不是很熟,能给个简单的示例吗?
    DrakeXiang
        3
    DrakeXiang  
       2022-04-07 11:40:51 +08:00
    为什么不能删掉 script/css ?
    Envov
        4
    Envov  
       2022-04-07 12:16:35 +08:00 via iPhone
    https://github.com/jantimon/html-webpack-plugin#configuration
    使用 templateContent 根据实际情况动态创建 html 内容,不用 template
    matthewzhong
        5
    matthewzhong  
    OP
       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
        6
    DrakeXiang  
       2022-04-07 19:29:39 +08:00
    我是问为什么你的模板不能删掉 script/css 。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2813 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:26 · PVG 21:26 · LAX 06:26 · JFK 09:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.