Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use file-loader and html-loader together

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.

like image 244
Francesco Belladonna Avatar asked May 02 '16 21:05

Francesco Belladonna


People also ask

Can webpack bundle html?

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.

Is file loader deprecated?

Use with url-loader or file-loaderurl-loader and file-loader are deprecated over Asset Modules in webpack v5.

What is the use of html loader?

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.

What helps to resolve import require () on a file into a URL and emits the file into output directory?

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.


1 Answers

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())
like image 145
Francesco Belladonna Avatar answered Sep 21 '22 21:09

Francesco Belladonna