Use file-loader and html-loader together
Asked Answered
G

1

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.

Gallium answered 2/5, 2016 at 21:35 Comment(0)
G
10

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())
Gallium answered 2/5, 2016 at 22:46 Comment(4)
You described the solution, but didn't post the solution. Config example?Dubitable
file-loader!extract-loader!html-loader was enough for me. Notice that for html-loader I used also '?root=' + encodeURIComponent(sourcePath.toString())Gallium
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.Dubitable
It does not work with interpolation flag: file!extract!html?interpolate.Gantlet

© 2022 - 2024 — McMap. All rights reserved.