How can I work with anchor tags in webpack?

365 Views Asked by At

I must be missing something because there seems to be almost no documentation about parsing anchor tags in webpack. For example if I want to hash the name of html files which are linked to in my landing index page.

Just like this post says: Webpack html-loader error processing href in anchor tags. Even if I attempt to extend the supported tags in html-loader it results in errors. Here is the documentation about extending supported tags: https://webpack.js.org/loaders/html-loader/#list.

So what is so special about anchor>href tags?

1

There are 1 best solutions below

2
On

The example post you linked isn't using the spread (...) operator, which may be part of the issue if you're only trying to add sources instead of define a limited number of sources -- if you're specifically getting errors with other file types not being managed.

From the config file I created today, which works with anchor hrefs:

  module: {
    rules: [
      {
        test: /\.(jpg|svg|png|pdf|gif)$/,
        type: "asset/resource",
      },
      {
        test: /\.html$/,
        loader: "html-loader",
        options: {
          sources: {
            list: [
              // All default supported tags and attributes
              "...",
              {
                tag: "a",
                attribute: "href",
                type: "src",
              },
            ],
          },
        },
      },
    ], 
  }

Without the "..." in the list: array above, webpack replaces its sources with those listed instead of adding the new sources to the existing list.

I am specifically using this config to grab a PDF asset in my src/ folder from an anchor tag in my HTML, copy it to dist/ and update its href in the final build, and this is working correctly for me.