html-loader-withhook
v5.2.0
Published
Enhanced html-loader with tag/attribute hooks support
Maintainers
Readme
html-loader-withhook
Enhanced HTML loader with Hooks support for webpack.
新增功能
- 支持标签处理器 Hook
- 支持属性处理器 Hook
- 继承原 html-loader 所有功能
安装
npm install --save-dev html-loader-withhook基础配置
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader-withhook",
},
],
},
};Hook 选项
sources.tags
类型:
type TagHandler = (
params: {
value: string;
startOffset: number;
endOffset: number;
resourcePath: string;
},
sources: Array<Source>,
) => boolean | void;
type tags = {
[tagName: string]: TagHandler;
};允许为特定标签注册处理器:
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader-withhook",
options: {
sources: {
tags: {
// 处理 img 标签
img: (params, sources) => {
sources.push({
name: "data-src",
value: params.value,
isValueQuoted: false,
startOffset: params.startOffset,
endOffset: params.endOffset,
});
return true; // 返回 true 表示处理完成,阻断后续处理
},
},
},
},
},
],
},
};sources.attributes
类型:
type AttributeHandler = (
params: {
tagName: string;
value: string;
startOffset: number;
endOffset: number;
resourcePath: string;
},
sources: Array<Source>,
) => boolean | void;
type attributes = {
[attributeName: string]: AttributeHandler;
};允许为特定属性注册处理器:
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader-withhook",
options: {
sources: {
attributes: {
// 处理 src 属性
src: (params, sources) => {
if (params.tagName === "img") {
sources.push({
name: "data-src",
value: params.value,
isValueQuoted: true,
startOffset: params.startOffset,
endOffset: params.endOffset,
});
return true; //返回 true 表示处理完成,阻断后续处理
}
},
},
},
},
},
],
},
};示例
图片懒加载处理
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader-withhook",
options: {
sources: {
tags: {
img: (params, sources) => {
// 将 src 转换为 data-src
sources.push({
name: "data-src",
value: params.value,
isValueQuoted: true,
startOffset: params.startOffset,
endOffset: params.endOffset,
});
return true;
},
},
},
},
},
],
},
};自定义属性处理
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader-withhook",
options: {
sources: {
attributes: {
"custom-src": (params, sources) => {
sources.push({
name: "src",
value: `/assets/${params.value}`,
isValueQuoted: true,
startOffset: params.startOffset,
endOffset: params.endOffset,
});
return true;
},
},
},
},
},
],
},
};Hook 执行流程
- 解析HTML注释忽略标记
- 执行标签级hook(返回true则跳过后续处理)
- 执行属性级hook(返回true则跳过默认处理)
- 应用原始处理规则
错误处理机制
Hook 执行过程中的错误会被收集并通过 webpack 的错误系统报告。每个错误都包含:
- Hook 的类型(标签/属性)
- Hook 的名称
- 错误信息
继承功能
html-loader-withhook 完全兼容原版 html-loader 的所有功能,包括:
- 源码处理
- 预处理器
- 后处理器
- 最小化
- ES 模块支持
详细说明请参考原版 html-loader 文档。
License
MIT
