jharris4 / html-webpack-tags-plugin

lets you define html tags to inject with html-webpack-plugin
MIT License
256 stars 31 forks source link

Attributes not added to scripts in head #79

Closed jjaanila closed 2 years ago

jjaanila commented 2 years ago

I have a bunch of scripts coming from CDN and I inject them into index.html like this:

new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'public/index.html',
  chunks: ['main'],
  inject: true
}),
new HtmlWebpackTagsPlugin({
  tags: [],
  usePublicPath: false,
  append: false,
  scripts: [
    {
      path: `<CDN path of react>`,
      external: {
        packageName: 'react',
        variableName: 'React',
      },
      attributes: {
        type: 'text/javascript',
        crossorigin: 'anonymous'
      }
    }
  ]
})

The scripts are prepended fine into head, but the configured attributes are not added. I think the root cause is on this line

https://github.com/jharris4/html-webpack-tags-plugin/blob/acdccfc8cab6773a33820ccde138e6c3f08fca87/index.js#L548

which assumes that all scripts will be in body. A possible fix would be to concat pluginHead and pluginBody before filtering, but please correct me if I'm wrong. I don't know much about webpack plugin development.

Package versions:

webpack@5.51.1
html-webpack-plugin@5.3.2
html-webpack-tags-plugin@3.0.1
jharris4 commented 2 years ago

Hi, thanks for reporting this issue! It looks like you are correct about the tags not being in the body anymore by default.

This seems to be caused by changes to the logic in the HtmlWebpackPlugin's logic for where script tags get injected.

They used to always be injected in the body, but now it depends on the values of the inject and scriptLoading options. I'll see if I can find the time soon to fix this (and add tests for it). But a PR to fix it would of course be welcome as well!

jharris4 commented 2 years ago

I've fixed the issue (and added some e2e tests for it) and published version 3.0.2 with the fix. Thanks for reporting the issue, and please do let me know if you find any further issues!

jjaanila commented 2 years ago

3.0.2 does indeed fix the issue. Thanks a lot! :medal_sports: