.box{
width:100px;
height:100px;
background-image:url('./public/img.jpg')}
webpack无法直接找到public文件夹,需要将url里面的路径转为require引入的形式
function loader(source){
let reg=/url\((.+?)\)/g
let pos=0;
let current;
let arr=['let list=[]'];
while(current=reg.exec(source)){
let [matchUrl,g]=current;
let last=reg.lastIndex-matchUrl.length;
arr.push(`last.push(${JSON.stringify(source.slice(pos,last))})`);
pos=reg.lastIndex;
arr.push(`list.push('url('+require(${g})+')')`)
}
arr.push(`list.push(${JSON.stringify(source.slice(pos))})`)
arr.push(`module.exports=list.join('')`);
return source;
}
还需要改造style-loader
let loaderUtils=require('loader-utils');
function loader(source){
let str=`let style=document.createElement('style');
style.innerHTML=${JSON.stringify(source)};
document.head.appendChild(style);`
return str;
}
loader.pitch=function(remainingRequest){
let str=`let style=document.createElement('style');
style.innerHTML=require(${loaderUtils.stringifyRequest(this,'!!'+remainingRequest)});
document.head.appendChild(style)`
return str;
}
module.exports=loader