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.
The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation.
Use with url-loader or file-loaderurl-loader and file-loader are deprecated over Asset Modules in webpack v5.
The html-loader defination says that it exports html as String (What does it mean). it also says that every loadable attributes (for example <img src="image. png" is imported as require('./image. png') ,and you may need to specify loader for images in your configuration ( file-loader or url-loader ), What does it mean.
svg . Webpack goes through all the import ed and require d files in your project, and for all those files which have a . svg extension, it uses as an input to the webpack file loader. For each of these files, the file loader emits the file in the output directory and resolves the correct URL to be referenced.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With