用途
1.对于不稳定的图片资源,使用一张图片加以替换
2.解决安全问题,对于“Web 应用程序包含了不存在的域的链接”的安全错误,在appscan扫描时往往会遇到
项目里使用
npm i bundle-url-check-loader -D
github地址
对你有帮助的话可以star一下
主要核心思想:
AST
- 使用node:https和node:http发起网络请求 ,这里需要区分请求-响应协议,应该我们的链接可能是http或者https
- url 是 String 类型的字面量即StringLiteral,配合正则表达式可以排出非url类型的StringLiteral
- 由于网络请求是异步的,需要配合this.async()告知 loader runner 等待异步结果返回
- source若包含多个图片URL会发起多个网络请求,这时需要使用 promiseAll组织所有promise的返回,使用 count 计数
- 当source中所有图片URL的请求全部执行完毕时Promise.all(promiseAll)给出返回值,这里再使用generator将检测替换新value 后的 AST转换成 js,并使用 callback告知loader runner执行完毕
- 当遇到的请求链接是无法响应的,我们需要从error的回调函数里去替换url
Example
1.例如,遇到项目bundle中存在不安全(不可访问)的链接,webpack.config.js传url为空,即可将其删除,url则是编写对应的正则表达式去匹配不安全(不可访问)的链接
const checkAUrlList = [
"http://schemas.microsoft.com/office/excel/2006/main",
"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
"https://zhihu.com",
];
for (let i = 0; i < 3; i++) {
var a = document.createElement("a");
a.setAttribute("href", checkAUrlList[i]);
a.innerHTML='URL';
document.getElementById("body").appendChild(a);
}
webpack.config.js
module.exports = {
...
module: {
rules: [
{
test: /\.js$/,
use:[{
loader:"bundle-url-check-loader",
options:{
url:'',
reg:[/^http[s]{0,1}:\/\/schemas\.\S*/]
}
}],
},
],
},
};
...
有什么使用上的问题或者有什么建议,可以留言