6

I'm working on an angular application which requires html files to be extracted as plain HTML files and at same time should check for any <img src="..."> to require those images (as assets). In addition, images are based upon root path (so /images/something.png), they need to be resolved relatively to webpack context setting (the base path).

How can I achieve this? Can't get html-loader to play nicely with file-loader. Since the former outputs a JS file (with the require statements) and the latter expects a plain HTML file.

Francesco Belladonna
  • 11,361
  • 12
  • 77
  • 147

1 Answers1

9

I found the solution by myself by digging a lot into source codes of the loaders in question.

Basically, it doesn't work by default because file-loader expects a "raw" file, so if you want to output an HTML file, you need to have html source, not a JS one. However, html-loader takes an HTML file and outputs a JS file (with require assets and the content).

The solution was this deeply hidden and fantastic extract-loader which parses the JS coming out of html-loader, converts it back to plain html, the assets are still required and replaced even with hash for cachebusting.

That's perfect, you pass the output to file-loader and you finally have your html files!

Example configuration

In my case, my loader configuration looks like:

'file-loader!extract-loader!html-loader' + '?root=' + encodeURIComponent(sourcePath.toString())
Francesco Belladonna
  • 11,361
  • 12
  • 77
  • 147
  • 2
    You described the solution, but didn't post the solution. Config example? – Benny Bottema Jul 18 '16 at 07:55
  • `file-loader!extract-loader!html-loader` was enough for me. Notice that for html-loader I used also `'?root=' + encodeURIComponent(sourcePath.toString())` – Francesco Belladonna Jul 18 '16 at 10:16
  • Yes, I was pulling my hair to find out why the src="/url" was begin ignored until I read that root url's are ignored by default. You used ?root=, while I switched to relative url's. Both work. Thanks. – Benny Bottema Jul 18 '16 at 11:32
  • 1
    It does not work with *interpolation* flag: `file!extract!html?interpolate`. – vbarbarosh Oct 04 '16 at 09:34