V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
matthewzhong
V2EX  ›  问与答

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

  •  
  •   matthewzhong · Apr 6, 2022 · 1441 views
    This topic created in 1483 days ago, the information mentioned may be changed or developed.

    一个小的静态网站,目录结构就是 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 replies    2022-04-07 19:29:39 +08:00
    noe132
        1
    noe132  
       Apr 6, 2022
    那问题来了,为什么不能把原来的模板改一下?
    matthewzhong
        2
    matthewzhong  
    OP
       Apr 6, 2022
    @noe132 加环境判断吗? webpack 不是很熟,能给个简单的示例吗?
    DrakeXiang
        3
    DrakeXiang  
       Apr 7, 2022
    为什么不能删掉 script/css ?
    Envov
        4
    Envov  
       Apr 7, 2022 via iPhone
    https://github.com/jantimon/html-webpack-plugin#configuration
    使用 templateContent 根据实际情况动态创建 html 内容,不用 template
    matthewzhong
        5
    matthewzhong  
    OP
       Apr 7, 2022
    @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  
       Apr 7, 2022
    我是问为什么你的模板不能删掉 script/css 。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1142 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 78ms · UTC 18:14 · PVG 02:14 · LAX 11:14 · JFK 14:14
    ♥ Do have faith in what you're doing.