html-loader | webpack (2023)

html-loader | webpack (1)html-loader | webpack (2)html-loader | webpack (3)html-loader | webpack (4)html-loader | webpack (5)html-loader | webpack (6)

Exports HTML as string. HTML is minimized when the compiler demands.

Getting Started

To begin, you'll need to install html-loader:

npm install --save-dev html-loader

or

yarn add -D html-loader

or

pnpm add -D html-loader

Then add the plugin to your webpack config. For example:

file.js

import html from "./file.html";

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", }, ], },};

Options

  • sources
  • preprocessor
  • minimize
  • esModule

sources

Type:

type sources = | boolean | { list?: Array<{ tag?: string; attribute?: string; type?: string; filter?: ( tag: string, attribute: string, attributes: string, resourcePath: string ) => boolean; }>; urlFilter?: ( attribute: string, value: string, resourcePath: string ) => boolean; scriptingEnabled?: boolean; };

Default: true

By default every loadable attributes (for example - <img src="image.png"/>) is imported (const img = require('./image.png') or import img from "./image.png"").You may need to specify loaders for images in your configuration (recommended asset modules).

Supported tags and attributes:

  • the src attribute of the audio tag
  • the src attribute of the embed tag
  • the src attribute of the img tag
  • the srcset attribute of the img tag
  • the src attribute of the input tag
  • the data attribute of the object tag
  • the src attribute of the script tag
  • the href attribute of the script tag
  • the xlink:href attribute of the script tag
  • the src attribute of the source tag
  • the srcset attribute of the source tag
  • the src attribute of the track tag
  • the poster attribute of the video tag
  • the src attribute of the video tag
  • the xlink:href attribute of the image tag
  • the href attribute of the image tag
  • the xlink:href attribute of the use tag
  • the href attribute of the use tag
  • the href attribute of the link tag when the rel attribute contains stylesheet, icon, shortcut icon, mask-icon, apple-touch-icon, apple-touch-icon-precomposed, apple-touch-startup-image, manifest, prefetch, preload or when the itemprop attribute is image, logo, screenshot, thumbnailurl, contenturl, downloadurl, duringmedia, embedurl, installurl, layoutimage
  • the imagesrcset attribute of the link tag when the rel attribute contains stylesheet, icon, shortcut icon, mask-icon, apple-touch-icon, apple-touch-icon-precomposed, apple-touch-startup-image, manifest, prefetch, preload
  • the content attribute of the meta tag when the name attribute is msapplication-tileimage, msapplication-square70x70logo, msapplication-square150x150logo, msapplication-wide310x150logo, msapplication-square310x310logo, msapplication-config, twitter:image or when the property attribute is og:image, og:image:url, og:image:secure_url, og:audio, og:audio:secure_url, og:video, og:video:secure_url, vk:image or when the itemprop attribute is image, logo, screenshot, thumbnailurl, contenturl, downloadurl, duringmedia, embedurl, installurl, layoutimage
  • the icon-uri value component in content attribute of the meta tag when the name attribute is msapplication-task

boolean

The true value enables processing of all default elements and attributes, the false disable processing of all attributes.

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: false, }, }, ], },};

object

Allows you to specify which tags and attributes to process, filter them, filter urls and process sources starts with /.

For example:

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { list: [ "...", { tag: "img", attribute: "data-src", type: "src", }, { tag: "img", attribute: "data-srcset", type: "srcset", }, ], urlFilter: (attribute, value, resourcePath) => { if (/example\.pdf$/.test(value)) { return false; } return true; }, }, }, }, ], },};

list

Type:

(Video) Learn Webpack Pt. 8: Html-loader, File-loader, & Clean-webpack

type list = Array<{ tag?: string; attribute?: string; type?: string; filter?: ( tag: string, attribute: string, attributes: string, resourcePath: string ) => boolean;}>;

Default: supported tags and attributes.

Allows to setup which tags and attributes to process and how, and the ability to filter some of them.

Using ... syntax allows you to extend default supported tags and attributes.

For example:

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { list: [ "...", { tag: "img", attribute: "data-src", type: "src", }, { tag: "img", attribute: "data-srcset", type: "srcset", }, { tag: "link", attribute: "href", type: "src", filter: (tag, attribute, attributes, resourcePath) => { if (/my-html\.html$/.test(resourcePath)) { return false; } if (!/stylesheet/i.test(attributes.rel)) { return false; } if ( attributes.type && attributes.type.trim().toLowerCase() !== "text/css" ) { return false; } return true; }, }, ], }, }, }, ], },};

If the tag name is not specified it will process all the tags.

You can use your custom filter to specify html elements to be processed.

For example:

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { list: [ { attribute: "src", type: "src", filter: (tag, attribute, attributes, resourcePath) => { return tag.toLowerCase() !== "img"; }, }, ], }, }, }, ], },};

Filter can also be used to extend the supported elements and attributes.

For example, filter can help process meta tags that reference assets:

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { list: [ { tag: "meta", attribute: "content", type: "src", filter: (tag, attribute, attributes, resourcePath) => { if ( attributes.value === "og:image" || attributes.name === "twitter:image" ) { return true; } return false; }, }, ], }, }, }, ], },};

Note

source with a tag option takes precedence over source without.

Filter can be used to disable default sources.

For example:

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { list: [ "...", { tag: "img", attribute: "src", type: "src", filter: () => false, }, ], }, }, }, ], },};

urlFilter

Type:

type urlFilter = ( attribute: string, value: string, resourcePath: string) => boolean;

Default: undefined

Allow to filter urls. All filtered urls will not be resolved (left in the code as they were written).All non requestable sources (for example <img src="javascript:void(0)"/>) do not handle by default.

(Video) Module Bundlers Explained... Webpack, Rollup, Parcel, and Snowpack

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { urlFilter: (attribute, value, resourcePath) => { if (/example\.pdf$/.test(value)) { return false; } return true; }, }, }, }, ], },};

scriptingEnabled

Type:

type scriptingEnabled = boolean;

Default: true

By default, the parser in html-loader interprets content inside <noscript> tags as #text, so processing of content inside this tag will be ignored.

In order to enable processing inside <noscript> for content recognition by the parser as #AST, set this parameter to: false

Additional information: scriptingEnabled

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { sources: { scriptingEnabled: false, }, }, }, ], },};

preprocessor

Type:

type preprocessor = ( content: string | Buffer, loaderContext: LoaderContext) => HTMLElement;

Default: undefined

Allows pre-processing of content before handling.

Warning

You should always return valid HTML

file.hbs

<div> <p>{{firstname}} {{lastname}}</p> <img src="image.png" alt="alt" /><div>

function

You can set the preprocessor option as a function instance.

webpack.config.js

const Handlebars = require("handlebars");module.exports = { module: { rules: [ { test: /\.hbs$/i, loader: "html-loader", options: { preprocessor: (content, loaderContext) => { let result; try { result = Handlebars.compile(content)({ firstname: "Value", lastname: "OtherValue", }); } catch (error) { loaderContext.emitError(error); return content; } return result; }, }, }, ], },};

You can also set the preprocessor option as an asynchronous function instance.

For example:

webpack.config.js

const Handlebars = require("handlebars");module.exports = { module: { rules: [ { test: /\.hbs$/i, loader: "html-loader", options: { preprocessor: async (content, loaderContext) => { let result; try { result = await Handlebars.compile(content)({ firstname: "Value", lastname: "OtherValue", }); } catch (error) { await loaderContext.emitError(error); return content; } return result; }, }, }, ], },};

minimize

Type:

(Video) Webpack 5 Crash Course | Frontend Development Setup

type minimize = | boolean | { caseSensitive?: boolean; collapseWhitespace?: boolean; conservativeCollapse?: boolean; keepClosingSlash?: boolean; minifyCSS?: boolean; minifyJS?: boolean; removeComments?: boolean; removeRedundantAttributes?: boolean; removeScriptTypeAttributes?: boolean; removeStyleLinkTypeAttributes?: boolean; };

Default: true in production mode, otherwise false

Tell html-loader to minimize HTML.

boolean

The enabled rules for minimizing by default are the following ones:

({ caseSensitive: true, collapseWhitespace: true, conservativeCollapse: true, keepClosingSlash: true, minifyCSS: true, minifyJS: true, removeComments: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true,});

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { minimize: true, }, }, ], },};

object

webpack.config.js

See html-minifier-terser's documentation for more information on the available options.

The default rules can be overridden using the following options in your webpack.conf.js

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { minimize: { removeComments: false, collapseWhitespace: false, }, }, }, ], },};

The default rules can be extended:

webpack.config.js

const { defaultMinimizerOptions } = require("html-loader");module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { minimize: { ...defaultMinimizerOptions, removeComments: false, collapseWhitespace: false, }, }, }, ], },};

esModule

Type:

type esModule = boolean;

Default: true

By default, html-loader generates JS modules that use the ES modules syntax.There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.

You can enable a CommonJS modules syntax using:

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { esModule: false, }, }, ], },};

Examples

Disable url resolving using the `` comment

With `` comment, can to disable sources handling for next tag.

<img src="image.png" /><img srcset="image.png 480w, image.png 768w" src="image.png" alt="Elva dressed as a fairy"/><meta itemprop="image" content="./image.png" /><link rel="icon" type="image/png" sizes="192x192" href="./image.png" />

roots

With resolve.roots can specify a list of directories where requests of server-relative URLs (starting with '/') are resolved.

webpack.config.js

(Video) WHAT IS WEBPACK, HOW DOES IT WORK? | Webpack 2 Basics Tutorial

module.exports = { context: __dirname, module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: {}, }, { test: /\.jpg$/, type: "asset/resource", }, ], }, resolve: { roots: [path.resolve(__dirname, "fixtures")], },};

file.html

<img src="/image.jpg" />

CDN

webpack.config.js

module.exports = { module: { rules: [ { test: /\.jpg$/, type: "asset/resource", }, { test: /\.png$/, type: "asset/inline", }, ], }, output: { publicPath: "http://cdn.example.com/[fullhash]/", },};

file.html

<img src="image.jpg" data-src="image2x.png" />

index.js

require("html-loader!./file.html");
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"src","type":"src"},{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');

Process script and link tags

script.file.js

console.log(document);

style.file.css

a { color: red;}

file.html

<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <title>Title of the document</title> <link rel="stylesheet" type="text/css" href="./style.file.css" /> </head> <body> Content of the document...... <script src="./script.file.js"></script> </body></html>

webpack.config.js

module.exports = { module: { rules: [ { test: /\.html$/, type: "asset/resource", generator: { filename: "[name][ext]", }, }, { test: /\.html$/i, use: ["html-loader"], }, { test: /\.js$/i, exclude: /\.file.js$/i, loader: "babel-loader", }, { test: /\.file.js$/i, type: "asset/resource", }, { test: /\.css$/i, exclude: /\.file.css$/i, loader: "css-loader", }, { test: /\.file.css$/i, type: "asset/resource", }, ], },};

Templating

You can use any template system. Below is an example for handlebars.

file.hbs

<div> <p>{{firstname}} {{lastname}}</p> <img src="image.png" alt="alt" /><div>

webpack.config.js

const Handlebars = require("handlebars");module.exports = { module: { rules: [ { test: /\.hbs$/i, loader: "html-loader", options: { preprocessor: (content, loaderContext) => { let result; try { result = Handlebars.compile(content)({ firstname: "Value", lastname: "OtherValue", }); } catch (error) { loaderContext.emitError(error); return content; } return result; }, }, }, ], },};

PostHTML

You can use PostHTML without any additional loaders.

file.html

<img src="image.jpg" />

webpack.config.js

const posthtml = require("posthtml");const posthtmlWebp = require("posthtml-webp");module.exports = { module: { rules: [ { test: /\.hbs$/i, loader: "html-loader", options: { preprocessor: (content, loaderContext) => { let result; try { result = posthtml().use(plugin).process(content, { sync: true }); } catch (error) { loaderContext.emitError(error); return content; } return result.html; }, }, }, ], },};

Export into HTML files

A very common scenario is exporting the HTML into their own .html file, toserve them directly instead of injecting with javascript. This can be achievedwith a combination of 2 loaders:

and asset modules

The html-loader will parse the URLs, require the images and everything youexpect. The extract loader will parse the javascript back into a proper htmlfile, ensuring images are required and point to proper path, and the asset moduleswill write the .html file for you. Example:

webpack.config.js

(Video) Learn Webpack - Full Tutorial for Beginners

module.exports = { output: { assetModuleFilename: "[name][ext]", }, module: { rules: [ { test: /\.html$/, type: "asset/resource", generator: { filename: "[name][ext]", }, }, { test: /\.html$/i, use: ["html-loader"], }, ], },};

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

FAQs

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 is webpack loader? ›

Loaders are the node-based utilities built for webpack to help webpack to compile and/or transform a given type of resource that can be bundled as a javascript module. css-loader is the npm module that would help webpack to collect CSS from all the css files referenced in your application and put it into a string.

What is html webpack? ›

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.

Why do we need Webpacks? ›

This is why webpack exists. It's a tool that lets you bundle your JavaScript applications (supporting both ESM and CommonJS), and it can be extended to support many different assets such as images, fonts and stylesheets.

How do I make a loader in HTML? ›

To create a page loader, you simply need to:
  1. Create your HTML code to indicate what you want to use as your loader, e.g., an image or an icon.
  2. Then, style your loader page to your taste. ...
  3. Finally, create a JavaScript script that will fire up when the page is requested and then execute the code it contains.

How do I make a website loader? ›

How to Add Loading Animation to Website in 2 Minutes! - YouTube

Is webpack still used? ›

Loved by many, hated by some, known to all. And still the most popular bundler in 2021. With more than 15 million weekly downloads (at the time of writing this post), there's no doubt that Webpack is still the bundler par excellence in 2021.

What is Babel vs webpack? ›

If Babel is a translator for JS, you can think of Webpack as a mega-multi-translator that works with all kinds of languages (or assets). For example, Webpack often runs Babel as one of its jobs. Another example, Webpack can collect all your inline CSS styles in your Javascript files and bundle them into one.

Is webpack hard to learn? ›

One of the most difficult part of webpack is learning how to configure it. Particularly, setting up loaders for different workflows. I heard many times from devs that they don't understand how to configure webpack because of the config file.

What is a CSS loader? ›

CSS Loader being a front-end component is defined as an npm Module that collects all the CSS files referenced in the working application to help webpack and consolidate into a string. This compiles an application of a particular resource as a JavaScript module (CSS to JS file).

Can webpack bundle HTML? ›

This means Webpack has successfully bundled both our logic from src/index. js and HTML from src/index. html into the dist directory, even automatically linking them together for us. And this is just the beginning of what Webpack can do!

How does a webpack work? ›

Webpack is a module bundler. It takes disparate dependencies, creates modules for them and bundles the entire network up into manageable output files. This is especially useful for Single Page Applications (SPAs), which is the defacto standard for Web Applications today.

Are Webpacks popular? ›

Webpack is one of the most popular bundlers around today. Tons of production apps and frameworks, such as Next. js, Create React App, and more, use it for bundling and building. Additionally, it has the largest library of plugins out of any bundler.

Is webpack front end? ›

A comparison between Rollup and Webpack for React apps. — Webpack has been the most popular bundling tool for front-end development with React, and since both Create React App and Next.

What is grunt and webpack? ›

Grunt is a task runner built on node. js and Webpack is a module bundler built on javascript. Both have huge ecosystems with plenty of plugins/modules available. But why should you choose Webpack over Grunt? Since Grunt emphasizes configuration over code, configuring Grunt is a somewhat simple process.

What is preloader in HTML? ›

The preload attribute specifies if and how the author thinks that the media file should be loaded when the page loads. The preload attribute allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience.

What is a page loader? ›

A page loader is any kind of animation that visually communicates to a visitor that the page is loading and to just sit tight for a few seconds. Without a page loader, a visitor might think your site is being unresponsive and just click away in frustration.

How do you show loading in HTML? ›

STEP 1 : Include a DIV tag in the begining of a body tag and give the tag a Class or Id whatever its on you. for eg: id = "loading". STEP 2 : Now link a css file to your HTML file.

How do you make a spinning wheel in HTML? ›

The HTML Code

We have defined a wheel using <div> with id="wheel" and inside that defined two lines with id="line1" and id="line2" . We have defined a straight line using <div> with id="line3" where the wheel will spin. Defined a <button> element to handle start and stop functionality for the spinning wheel.

How do I add a loading page to my website? ›

Introduction
  1. Open any IDE here. I use VS Code which is free and developed by Microsoft.
  2. Create a project. In VS Code Add a workplace folder, open Explorer and add new file index.html.
  3. Code the home webpage you need in index. html. ...
  4. Do either step 4.1 or 4.2.
  5. Step 4.1. ...
  6. Step 4.2. ...
  7. Add the below script to end of head tag.
Dec 2, 2020

What is a website preloader? ›

A preloader is a static picture or animated css loaders displayed on-screen while the website is loading in the background. The preloader animation finishes when the site is fully loaded and ready to be shown, and your page is displayed to visitors. It's tedious to watch a page load element by element.

What is better than webpack? ›

Gulp: Gulp is the best alternative for webpack. It is an open-source JavaScript toolkit, used for streaming build systems in front-end web development. It is a task runner which is built on nom and node.

What's faster than webpack? ›

While a bundler-based workflow like Webpack will have to process your entire JavaScript modules before a single browser request, Vite only processes your dependency modules before a single browser request. This is why Vite is able to process your development build faster than Webpack.

Who uses webpack? ›

Who uses Webpack? 4178 companies reportedly use Webpack in their tech stacks, including Airbnb, Pinterest, and Instagram.

What is preloader in HTML? ›

The preload attribute specifies if and how the author thinks that the media file should be loaded when the page loads. The preload attribute allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience.

How do you use a preloader? ›

In Google Chrome right click anywhere on the page and click on inspect element, this will bring up the developer tools. Right click on the body element and add a new attribute class="loaded" . Hit enter and you'll see our preloader screen disappear.

How do you show loading in HTML? ›

STEP 1 : Include a DIV tag in the begining of a body tag and give the tag a Class or Id whatever its on you. for eg: id = "loading". STEP 2 : Now link a css file to your HTML file.

How do I use SCSS in HTML? ›

  1. Hey! Just use jsonformatter.org/scss-to-css and paste the SCSS code then it will transfer that code into CSS! All you need to do is copy the CSS output. ...
  2. You should Link style. css like normal because When you compile the SCSS file it will generate a CSS file and use that to apply the style you added. – Kasem777.

Videos

1. HTML + IMAGE LOADERS | Webpack 2 Basics Tutorial
(Academind)
2. Vite in 100 Seconds
(Fireship)
3. Webpack caching pt 1 - Hashing
(Fredrik Christenson)
4. WEBPACK + MULTIPLE HTML FILES | Webpack 2 Basics Tutorial
(Academind)
5. Learn Webpack Pt. 1: What Even Is Webpack??
(Colt Steele)
6. What is Webpack - academind.com Snippet
(Academind)
Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated: 09/30/2022

Views: 5896

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.