Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

HTML Loader

License

NotificationsYou must be signed in to change notification settings

webpack-contrib/html-loader

Repository files navigation

html-loaderwebpack

npmnodetestscoveragediscussionsize

html-loader

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

Getting Started

To begin, you'll need to installhtml-loader:

npm install --save-dev html-loader

or

yarn add -D html-loader

or

pnpm add -D html-loader

Then 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",},],},};

Options

sources

Type:

typesources=|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 -<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:

  • Thesrc attribute of theaudio tag
  • Thesrc attribute of theembed tag
  • Thesrc attribute of theimg tag
  • Thesrcset attribute of theimg tag
  • Thesrc attribute of theinput tag
  • Thedata attribute of theobject tag
  • Thesrc attribute of thescript tag
  • Thehref attribute of thescript tag
  • Thexlink:href attribute of thescript tag
  • Thesrc attribute of thesource tag
  • Thesrcset attribute of thesource tag
  • Thesrc attribute of thetrack tag
  • Theposter attribute of thevideo tag
  • Thesrc attribute of thevideo tag
  • Thexlink:href attribute of theimage tag
  • Thehref attribute of theimage tag
  • Thexlink:href attribute of theuse tag
  • Thehref attribute of theuse tag
  • Thehref attribute of thelink tag when therel attribute containsstylesheet,icon,shortcut icon,mask-icon,apple-touch-icon,apple-touch-icon-precomposed,apple-touch-startup-image,manifest,prefetch,preload or when theitemprop attribute isimage,logo,screenshot,thumbnailurl,contenturl,downloadurl,duringmedia,embedurl,installurl,layoutimage
  • Theimagesrcset attribute of thelink tag when therel attribute containsstylesheet,icon,shortcut icon,mask-icon,apple-touch-icon,apple-touch-icon-precomposed,apple-touch-startup-image,manifest,prefetch,preload
  • Thecontent attribute of themeta tag when thename attribute ismsapplication-tileimage,msapplication-square70x70logo,msapplication-square150x150logo,msapplication-wide310x150logo,msapplication-square310x310logo,msapplication-config,twitter:image or when theproperty attribute isog:image,og:image:url,og:image:secure_url,og:audio,og:audio:secure_url,og:video,og:video:secure_url,vk:image or when theitemprop attribute isimage,logo,screenshot,thumbnailurl,contenturl,downloadurl,duringmedia,embedurl,installurl,layoutimage
  • Theicon-uri value component incontent attribute of themeta tag when thename attribute ismsapplication-task

boolean

  • 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,},},],},};

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

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;},},},},],},};

list

Type:

typelist=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 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 tagreturntag.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,},],},},},],},};

urlFilter

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;},},},},],},};

scriptingEnabled

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,},},},],},};

preprocessor

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>

function

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;},},},],},};

postprocessor

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>

function

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.replace(/<%=/g,isTemplateLiteralSupported ?`\${` :'" +').replace(/%>/g,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.replace(/<%=/g,isTemplateLiteralSupported ?`\${` :'" +').replace(/%>/g,isTemplateLiteralSupported ?"}" :'+ "').replace("my-value",value);},},},],},};

minimize

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.

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

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,},},},],},};

esModule

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,},},],},};

Examples

Disable URL resolving using the<!-- webpackIgnore: true --> comment

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"/>

roots

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 resolved

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

<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,..." >'

Processscript andlink tags

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",},],},};

Templating

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.

PostHTML

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;},},},],},};

Export into HTML files

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"],},],},};

Contributing

We welcome all contributions!If you're new here, please take a moment to review our contributing guidelines before submitting issues or pull requests.

CONTRIBUTING

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp