Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork204
webpack/html-loader
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Exports HTML as string. HTML is minimized when the compiler demands.
To begin, you'll need to installhtml-loader:
npm install --save-dev html-loaderor
yarn add -D html-loaderor
pnpm add -D html-loaderThen add the loader to yourwebpack configuration. For example:
file.js
importhtmlfrom"./file.html";
webpack.config.js
module.exports={module:{rules:[{test:/\.html$/i,loader:"html-loader",},],},};
Type:
typesources=|boolean|{list?:{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 -<img src="image.png">) is imported (const img = require('./image.png') ornew URL("./image.png", import.meta.url)).You may need to specify loaders for images in your configuration (recommendedasset modules).
Supported tags and attributes:
- The
srcattribute of theaudiotag - The
srcattribute of theembedtag - The
srcattribute of theimgtag - The
srcsetattribute of theimgtag - The
srcattribute of theinputtag - The
dataattribute of theobjecttag - The
srcattribute of thescripttag - The
hrefattribute of thescripttag - The
xlink:hrefattribute of thescripttag - The
srcattribute of thesourcetag - The
srcsetattribute of thesourcetag - The
srcattribute of thetracktag - The
posterattribute of thevideotag - The
srcattribute of thevideotag - The
xlink:hrefattribute of theimagetag - The
hrefattribute of theimagetag - The
xlink:hrefattribute of theusetag - The
hrefattribute of theusetag - The
hrefattribute of thelinktag when therelattribute containsstylesheet,icon,shortcut icon,mask-icon,apple-touch-icon,apple-touch-icon-precomposed,apple-touch-startup-image,manifest,prefetch,preloador when theitempropattribute isimage,logo,screenshot,thumbnailurl,contenturl,downloadurl,duringmedia,embedurl,installurl,layoutimage - The
imagesrcsetattribute of thelinktag when therelattribute containsstylesheet,icon,shortcut icon,mask-icon,apple-touch-icon,apple-touch-icon-precomposed,apple-touch-startup-image,manifest,prefetch,preload - The
contentattribute of themetatag when thenameattribute ismsapplication-tileimage,msapplication-square70x70logo,msapplication-square150x150logo,msapplication-wide310x150logo,msapplication-square310x310logo,msapplication-config,twitter:imageor when thepropertyattribute isog:image,og:image:url,og:image:secure_url,og:audio,og:audio:secure_url,og:video,og:video:secure_url,vk:imageor when theitempropattribute isimage,logo,screenshot,thumbnailurl,contenturl,downloadurl,duringmedia,embedurl,installurl,layoutimage - The
icon-urivalue component incontentattribute of themetatag when thenameattribute ismsapplication-task
- true: Enables processing of all default tags and attributes
- false: Disables processing entirely
webpack.config.js
module.exports={module:{rules:[{test:/\.html$/i,loader:"html-loader",options:{// Disables attributes processingsources:false,},},],},};
Allows you to specify which tags and attributes to process, filter them, filter URLs and process sources starting with/.
For example:
webpack.config.js
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 `attribute` argument contains a name of the HTML attribute.// The `value` argument contains a value of the HTML attribute.// The `resourcePath` argument contains a path to the loaded HTML file.if(/example\.pdf$/.test(value)){returnfalse;}returntrue;},},},},],},};
Type:
typelist={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 extenddefault supported tags and attributes.
For example:
webpack.config.js
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 nametag:"link",// Attribute nameattribute:"href",// Type of processing, can be `src` or `scrset`type:"src",// Allow to filter some attributesfilter:(tag,attribute,attributes,resourcePath)=>{// The `tag` argument contains a name of the HTML tag.// The `attribute` argument contains a name of the HTML attribute.// The `attributes` argument contains all attributes of the tag.// The `resourcePath` argument contains a path to the loaded HTML file.if(/my-html\.html$/.test(resourcePath)){returnfalse;}if(!/stylesheet/i.test(attributes.rel)){returnfalse;}if(attributes.type&&attributes.type.trim().toLowerCase()!=="text/css"){returnfalse;}returntrue;},},],},},},],},};
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 nameattribute:"src",// Type of processing, can be `src` or `scrset`type:"src",// Allow to filter some attributes (optional)filter:(tag,attribute,attributes,resourcePath)=>// The `tag` argument contains a name of the HTML tag.// The `attribute` argument contains a name of the HTML attribute.// The `attributes` argument contains all attributes of the tag.// The `resourcePath` argument contains a path to the loaded HTML file.// choose all HTML tags except img tagtag.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"){returntrue;}returnfalse;},},],},},},],},};
Note
source with atag 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,},],},},},],},};
Type:
typeurlFilter=(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<img src="#">) are not handled by default.
module.exports={module:{rules:[{test:/\.html$/i,loader:"html-loader",options:{sources:{urlFilter:(attribute,value,resourcePath)=>{// The `attribute` argument contains a name of the HTML attribute.// The `value` argument contains a value of the HTML attribute.// The `resourcePath` argument contains a path to the loaded HTML file.if(/example\.pdf$/.test(value)){returnfalse;}returntrue;},},},},],},};
Type:
typescriptingEnabled=boolean;
Default:true
By default, the parser inhtml-loader interprets content inside<noscript> tags as plain#text, so processing of content inside these tags will is ignored during processing.
In order to enable processing inside<noscript> for content recognition by the parser as#AST, set this option to:false
Additional information:scriptingEnabled
webpack.config.js
module.exports={module:{rules:[{test:/\.html$/i,loader:"html-loader",options:{sources:{// Enables processing inside the <noscript> tagscriptingEnabled:false,},},},],},};
Type:
typepreprocessor=(content:string,loaderContext:LoaderContext)=>string;
Default:undefined
Allows pre-processing of content before handling by the loader.
Warning
You should always return valid HTML.
file.hbs
<div> <p>{{firstname}}{{lastname}}</p> <imgsrc="image.png"alt="alt" /><div>
You can set thepreprocessor option as afunction instance.
webpack.config.js
constHandlebars=require("handlebars");module.exports={module:{rules:[{test:/\.hbs$/i,loader:"html-loader",options:{preprocessor:(content,loaderContext)=>{letresult;try{result=Handlebars.compile(content)({firstname:"Value",lastname:"OtherValue",});}catch(error){loaderContext.emitError(error);returncontent;}returnresult;},},},],},};
You can also set thepreprocessor option as an asynchronous function instance.
For example:
webpack.config.js
constHandlebars=require("handlebars");module.exports={module:{rules:[{test:/\.hbs$/i,loader:"html-loader",options:{preprocessor:async(content,loaderContext)=>{letresult;try{result=awaitHandlebars.compile(content)({firstname:"Value",lastname:"OtherValue",});}catch(error){awaitloaderContext.emitError(error);returncontent;}returnresult;},},},],},};
Type:
typepostprocessor=(content:string,loaderContext:LoaderContext)=>string;
Default:undefined
Allows post-processing of content after replacing all attributes (likesrc/srcset/etc).
file.html
<imgsrc="image.png"/><imgsrc="<%= 'Hello ' + (1+1) %>"/><imgsrc="<%= require('./image.png') %>"/><imgsrc="<%= new URL('./image.png', import.meta.url) %>"/><div><%= require('./gallery.html').default %></div>
You can set thepostprocessor option as afunction instance.
webpack.config.js
constHandlebars=require("handlebars");module.exports={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 themconstisTemplateLiteralSupported=content[0]==="`";returncontent.replaceAll("<%=",isTemplateLiteralSupported ?"${" :'" +').replaceAll("%>",isTemplateLiteralSupported ?"}" :'+ "');},},},],},};
You can also set thepostprocessor option as an asynchronousfunction instance.
For example:
webpack.config.js
constHandlebars=require("handlebars");module.exports={module:{rules:[{test:/\.hbs$/i,loader:"html-loader",options:{postprocessor:async(content,loaderContext)=>{constvalue=awaitgetValue();// When you environment supports template literals (using browserslist or options) we will generate code using themconstisTemplateLiteralSupported=content[0]==="`";returncontent.replaceAll("<%=",isTemplateLiteralSupported ?"${" :'" +').replaceAll("%>",isTemplateLiteralSupported ?"}" :'+ "').replace("my-value",value);},},},],},};
Type:
typeminimize=|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, otherwisefalse
Use this option to enable or customize HTML minimization withhtml-loader.
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,},},],},};
webpack.config.js
Seehtml-minifier-terser's documentation for more information on the available options.
The default rules can be overridden using the following options in yourwebpack.config.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,},},},],},};
Type:
typeesModule=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, such asmodule concatenation andtree shaking.
If you want to generate CommonJS modules instead (e.g.,module.exports =), set:
webpack.config.js
module.exports={module:{rules:[{test:/\.html$/i,loader:"html-loader",options:{esModule:false,},},],},};
Use the<!-- webpackIgnore: true --> comment to prevent html-loader from processing URLs for the next HTML tag. This is useful when you don’t want Webpack to handle asset imports automatically.
<!-- Disabled url handling for the src attribute --><!-- webpackIgnore: true --><imgsrc="image.png"/><!-- Disabled url handling for the src and srcset attributes --><!-- webpackIgnore: true --><imgsrcset="image.png 480w, image.png 768w"src="image.png"alt="Elva dressed as a fairy"/><!-- Disabled url handling for the content attribute --><!-- webpackIgnore: true --><metaitemprop="image"content="./image.png"/><!-- Disabled url handling for the href attribute --><!-- webpackIgnore: true --><linkrel="icon"type="image/png"sizes="192x192"href="./image.png"/>
Withresolve.roots one can specify a list of directories where requests of server-relative URLs (starting with '/') are resolved.
webpack.config.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")],},};
file.html
<imgsrc="/image.jpg"/>
// => image.jpg in __dirname/fixtures will be resolvedwebpack.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
<imgsrc="image.jpg"data-src="image2x.png"/>
index.js
require("html-loader!./file.html");// => '<img src="http://cdn.example.com/49eba9f/a992ca.jpg" data-src="image2x.png">'
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');// => '<img src="image.jpg" data-src="data:image/png;base64,..." >'
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"src","type":"src"},{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');// => '<img src="http://cdn.example.com/49eba9f/a992ca.jpg" data-src="data:image/png;base64,..." >'
script.file.js
console.log(document);
style.file.css
a {color: red;}
file.html
<!doctype html><html><head><metacharset="UTF-8"/><title>Title of the document</title><linkrel="stylesheet"type="text/css"href="./style.file.css"/></head><body> Content of the document......<scriptsrc="./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",},],},};
You can use any templating engine by leveraging the preprocessor option in html-loader. The preprocessor function receives the file content and the loader context, allowing you to transform the HTML before it’s processed by webpack.
Below is an example forhandlebars.
file.hbs
<div> <p>{{firstname}}{{lastname}}</p> <imgsrc="image.png"alt="alt" /><div>
webpack.config.js
constHandlebars=require("handlebars");module.exports={module:{rules:[{test:/\.hbs$/i,loader:"html-loader",options:{preprocessor:(content,loaderContext)=>{letresult;try{result=Handlebars.compile(content)({firstname:"Value",lastname:"OtherValue",});}catch(error){loaderContext.emitError(error);returncontent;}returnresult;},},},],},};
This setup will transform thefile.hbs template using Handlebars before passing the result tohtml-loader.
You can usePostHTML to transform HTML before it's processed, without needing additional loaders.This is useful for tasks like converting image formats, adding attributes, or restructuring markup.
file.html
<imgsrc="image.jpg"/>
webpack.config.js
constposthtml=require("posthtml");constposthtmlWebp=require("posthtml-webp");module.exports={module:{rules:[{test:/\.hbs$/i,loader:"html-loader",options:{preprocessor:(content,loaderContext)=>{letresult;try{result=posthtml().use(plugin).process(content,{sync:true});}catch(error){loaderContext.emitError(error);returncontent;}returnresult.html;},},},],},};
A very common scenario is exporting the HTML into their own.html file, to serve them directly instead of injecting with javascript.This can be achieved with a combination of html-loader andasset 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 theasset moduleswill write the.html file for you. Example:
webpack.config.js
module.exports={output:{assetModuleFilename:"[name][ext]",},module:{rules:[{test:/\.html$/,type:"asset/resource",generator:{filename:"[name][ext]",},},{test:/\.html$/i,use:["html-loader"],},],},};
We welcome all contributions!If you're new here, please take a moment to review our contributing guidelines before submitting issues or pull requests.
About
HTML Loader
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.