Html loader module for webpack
npm install html-loader[![npm][npm]][npm-url]
[![node][node]][node-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![discussion][discussion]][discussion-url]
[![size][size]][size-url]
Exports HTML as string. HTML is minimized when the compiler demands.
To begin, you'll need to install html-loader:
``console`
npm install --save-dev html-loader
or
`console`
yarn add -D html-loader
or
`console`
pnpm add -D html-loader
Then add the plugin to your webpack config. For example:
file.js
`js`
import html from "./file.html";
webpack.config.js
`js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
},
],
},
};
- sources
- preprocessor
- postprocessor
- minimize
- esModule
Type:
`ts`
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 attribute (for example - 
) is imported (const img = require('./image.png') or new URL("./image.png", import.meta.url)).asset modules
You may need to specify loaders for images in your configuration (recommended ).
Supported tags and attributes:
- the src attribute of the audio tagsrc
- the attribute of the embed tagsrc
- the attribute of the img tagsrcset
- the attribute of the img tagsrc
- the attribute of the input tagdata
- the attribute of the object tagsrc
- the attribute of the script taghref
- the attribute of the script tagxlink:href
- the attribute of the script tagsrc
- the attribute of the source tagsrcset
- the attribute of the source tagsrc
- the attribute of the track tagposter
- the attribute of the video tagsrc
- the attribute of the video tagxlink:href
- the attribute of the image taghref
- the attribute of the image tagxlink:href
- the attribute of the use taghref
- the attribute of the use taghref
- the 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, layoutimageimagesrcset
- the 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, preloadcontent
- the 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, layoutimageicon-uri
- the value component in content attribute of the meta tag when the name attribute is msapplication-task
#### boolean
The true value enables the processing of all default elements and attributes, the false value disables the processing of all attributes.
webpack.config.js
`js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
// Disables attributes processing
sources: false,
},
},
],
},
};
#### object
Allows you to specify which tags and attributes to process, filter them, filter urls and process sources starting with /.
For example:
webpack.config.js
`jsattribute
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
// All default supported tags and attributes
"...",
{
tag: "img",
attribute: "data-src",
type: "src",
},
{
tag: "img",
attribute: "data-srcset",
type: "srcset",
},
],
urlFilter: (attribute, value, resourcePath) => {
// The argument contains a name of the HTML attribute.value
// The argument contains a value of the HTML attribute.resourcePath
// The argument contains a path to the loaded HTML file.
if (/example\.pdf$/.test(value)) {
return false;
}
return true;
},
},
},
},
],
},
};
`
#### list
Type:
`ts`
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, as well as the ability to filter some of them.
Using ... syntax allows you to extend default supported tags and attributes.
For example:
webpack.config.js
`jssrc
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
// All default supported tags and attributes
"...",
{
tag: "img",
attribute: "data-src",
type: "src",
},
{
tag: "img",
attribute: "data-srcset",
type: "srcset",
},
{
// Tag name
tag: "link",
// Attribute name
attribute: "href",
// Type of processing, can be or scrsettag
type: "src",
// Allow to filter some attributes
filter: (tag, attribute, attributes, resourcePath) => {
// The argument contains a name of the HTML tag.attribute
// The argument contains a name of the HTML attribute.attributes
// The argument contains all attributes of the tag.resourcePath
// The argument contains a path to the loaded HTML file.
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
`jssrc
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
{
// Attribute name
attribute: "src",
// Type of processing, can be or scrsettag
type: "src",
// Allow to filter some attributes (optional)
filter: (tag, attribute, attributes, resourcePath) => {
// The argument contains a name of the HTML tag.attribute
// The argument contains a name of the HTML attribute.attributes
// The argument contains all attributes of the tag.resourcePath
// The argument contains a path to the loaded HTML file.
// choose all HTML tags except img tag
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:
`js
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:
`js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
"...",
{
tag: "img",
attribute: "src",
type: "src",
filter: () => false,
},
],
},
},
},
],
},
};
#### urlFilter
Type:
`ts`
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).
Non-requestable sources (for example ) are not handled by default.
`jsattribute
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
urlFilter: (attribute, value, resourcePath) => {
// The argument contains a name of the HTML attribute.value
// The argument contains a value of the HTML attribute.resourcePath
// The argument contains a path to the loaded HTML file.
if (/example\.pdf$/.test(value)) {
return false;
}
return true;
},
},
},
},
],
},
};
`
#### scriptingEnabled
Type:
`ts`
type scriptingEnabled = boolean;
Default: true
By default, the parser in html-loader interprets content inside
In order to enable processing inside
Additional information: scriptingEnabled
webpack.config.js
`js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
// Enables processing inside the
Type:
`ts`
type preprocessor = (content: string, loaderContext: LoaderContext) => string;
Default: undefined
Allows pre-processing of content before handling.
> [!WARNING]
>
> You should always return valid HTML
file.hbs
` {{firstname}} {{lastname}} #### You can set the webpack.config.js module.exports = { try { return content; return result; You can also set the For example: webpack.config.js module.exports = { try { return content; return result; Type: Default: Allows post-processing of content after replacing all attributes (like file.html #### You can set the webpack.config.js module.exports = { return content You can also set the postprocessor For example: webpack.config.js ` module.exports = { return content Type: ` Default: true Tell html-loader #### boolean The enabled rules for minimizing by default are the following ones: ` webpack.config.js ` #### 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 ` The default rules can be extended: webpack.config.js ` module.exports = { Type: ` Default: true By default, html-loader You can enable a CommonJS modules syntax using: webpack.config.js ` With ` With resolve.roots webpack.config.js ` file.html ` ` webpack.config.js ` file.html ` index.js ` // => ' ` // => ' ` // => ' script.file.js ` style.file.css ` file.html ` webpack.config.js ` You can use any template system. Below is an example for handlebars. file.hbs ` {{firstname}} {{lastname}} webpack.config.js module.exports = { try { return content; return result; You can use PostHTML without any additional loaders. file.html webpack.config.js module.exports = { try { return content; return result.html; A very common scenario is exporting the HTML into their own _.html_ file, to serve them directly instead of injecting with javascript. The html-loader will parse the URLs, require the images and everything you webpack.config.js Please take a moment to read our contributing guidelines if you haven't yet done so. [npm]: https://img.shields.io/npm/v/html-loader.svghbs

`functionpreprocessor option as a function instance.`js`
const Handlebars = require("handlebars");
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: (content, loaderContext) => {
let result;
result = Handlebars.compile(content)({
firstname: "Value",
lastname: "OtherValue",
});
} catch (error) {
loaderContext.emitError(error);
}
},
},
},
],
},
};preprocessor option as an asynchronous function instance.`js`
const Handlebars = require("handlebars");
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: async (content, loaderContext) => {
let result;
result = await Handlebars.compile(content)({
firstname: "Value",
lastname: "OtherValue",
});
} catch (error) {
await loaderContext.emitError(error);
}
},
},
},
],
},
};`$3
ts`
type postprocessor = (content: string, loaderContext: LoaderContext) => string;undefinedsrc/srcset/etc).`html`
 %>)
<%= require('./gallery.html').default %>functionpostprocessor option as a function instance.`js";
const Handlebars = require("handlebars");
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
postprocessor: (content, loaderContext) => {
// When you environment supports template literals (using browserslist or options) we will generate code using them
const isTemplateLiteralSupported = content[0] === "
.replace(/<%=/g, isTemplateLiteralSupported ? \${ : '" +')
.replace(/%>/g, isTemplateLiteralSupported ? "}" : '+ "');
},
},
},
],
},
};
`` option as an asynchronous function instance.js
const Handlebars = require("handlebars");
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
postprocessor: async (content, loaderContext) => {
const value = await getValue();
// When you environment supports template literals (using browserslist or options) we will generate code using them
const isTemplateLiteralSupported = content[0] === "";
.replace(/<%=/g, isTemplateLiteralSupported ? \${ : '" +')
.replace(/%>/g, isTemplateLiteralSupported ? "}" : '+ "')
.replace("my-value", value);
},
},
},
],
},
};
``$3
ts`
type minimize =
| boolean
| {
caseSensitive?: boolean;
collapseWhitespace?: boolean;
conservativeCollapse?: boolean;
keepClosingSlash?: boolean;
minifyCSS?: boolean;
minifyJS?: boolean;
removeComments?: boolean;
removeRedundantAttributes?: boolean;
removeScriptTypeAttributes?: boolean;
removeStyleLinkTypeAttributes?: boolean;
}; in production mode, otherwise false to minimize HTML.js`
({
caseSensitive: true,
collapseWhitespace: true,
conservativeCollapse: true,
keepClosingSlash: true,
minifyCSS: true,
minifyJS: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
});js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
minimize: true,
},
},
],
},
};js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
minimize: {
removeComments: false,
collapseWhitespace: false,
},
},
},
],
},
};js
const { defaultMinimizerOptions } = require("html-loader");
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
minimize: {
...defaultMinimizerOptions,
removeComments: false,
collapseWhitespace: false,
},
},
},
],
},
};
`$3
ts`
type esModule = boolean; generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, such as module concatenation and tree shaking.js`
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
esModule: false,
},
},
],
},
};Examples
$3
comment, one can disable sources handling for next tag.html
srcset="image.png 480w, image.png 768w"
src="image.png"
alt="Elva dressed as a fairy"
/>
`$3
one can specify a list of directories where requests of server-relative URLs (starting with '/') are resolved.js`
module.exports = {
context: __dirname,
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {},
},
{
test: /\.jpg$/,
type: "asset/resource",
},
],
},
resolve: {
roots: [path.resolve(__dirname, "fixtures")],
},
};html`
js`
// => image.jpg in __dirname/fixtures will be resolved$3
js`
module.exports = {
module: {
rules: [
{
test: /\.jpg$/,
type: "asset/resource",
},
{
test: /\.png$/,
type: "asset/inline",
},
],
},
output: {
publicPath: "http://cdn.example.com/[fullhash]/",
},
};html`
js
require("html-loader!./file.html");
'
`js
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');
'
`js
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"src","type":"src"},{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');
'
`$3
js`
console.log(document);css`
a {
color: red;
}html`
Content of the document......
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",
},
],
},
};$3
hbs

``js`
const Handlebars = require("handlebars");
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: (content, loaderContext) => {
let result;
result = Handlebars.compile(content)({
firstname: "Value",
lastname: "OtherValue",
});
} catch (error) {
loaderContext.emitError(error);
}
},
},
},
],
},
};`$3
html`
`js`
const posthtml = require("posthtml");
const posthtmlWebp = require("posthtml-webp");
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: (content, loaderContext) => {
let result;
result = posthtml().use(plugin).process(content, { sync: true });
} catch (error) {
loaderContext.emitError(error);
}
},
},
},
],
},
};asset modules$3
This can be achieved with a combination of html-loader and .asset modules
expect. The extract loader will parse the javascript back into a proper html
file, ensuring images are required and point to proper path, and the `
will write the _.html_ file for you. Example:js``
module.exports = {
output: {
assetModuleFilename: "[name][ext]",
},
module: {
rules: [
{
test: /\.html$/,
type: "asset/resource",
generator: {
filename: "[name][ext]",
},
},
{
test: /\.html$/i,
use: ["html-loader"],
},
],
},
};Contributing
License
[npm-url]: https://npmjs.com/package/html-loader
[node]: https://img.shields.io/node/v/html-loader.svg
[node-url]: https://nodejs.org
[tests]: https://github.com/webpack-contrib/html-loader/workflows/html-loader/badge.svg
[tests-url]: https://github.com/webpack-contrib/html-loader/actions
[cover]: https://codecov.io/gh/webpack-contrib/html-loader/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack-contrib/html-loader
[discussion]: https://img.shields.io/github/discussions/webpack/webpack
[discussion-url]: https://github.com/webpack/webpack/discussions
[size]: https://packagephobia.now.sh/badge?p=html-loader
[size-url]: https://packagephobia.now.sh/result?p=html-loader