Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
解析相对 css 文件的图片路径
/**
* 解析相对 css 文件的图片路径
*
* @param baseurl
* @returns {undefined}
*/
function resolveTo (baseurl) {
return function (relativePath) {
// 绝对路径
if (relativePath[0] === '/') {
return location.origin + relativePath[0]
} else if (relativePath.startsWith('data:')) {
return relativePath
}
let url = new URL(baseurl)
let origin = url.origin
let segs = `${origin}${url.pathname}`.split('/')
segs.pop() // 去掉文件名
let relativeSegs = relativePath.split('/')
let seg
do {
seg = relativeSegs[0]
if (seg === '.') {
relativeSegs.shift()
} else if (seg === '..') {
relativeSegs.shift()
segs.pop()
} else {
break;
}
} while (seg)
return segs.concat(relativeSegs).join('/')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.