Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: 修复css中图片url解析错误 #681

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

zhcxk1998
Copy link

@zhcxk1998 zhcxk1998 commented Aug 25, 2023

  • 提交符合commit规范
详细描述
  • 复现路径
    子应用编写以下样式,base64图片中svg的填充路径被替换
/* 替换前 */
background: url(data:image/svg+xml;charset=utf-8,<svg><path fill='url(#a)'></path></svg>);
/* 替换后 */
background: url(data:image/svg+xml;charset=utf-8,<svg><path fill='url(replaceHost#a)'></path></svg>);
  • 原因
    原先正则 /(url\((?!['"]?(?:data):)['"]?)([^'")]*)(['"]?\))/g;,会先忽略data开头,导致匹配到内部的fill='url(#a)'中的#a进行路径替换
image
  • 解决方案
    修改正则表达式为/url\((['"]?)((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)(\1)\)/g,先匹配url(xxx)内的xxx,包含嵌套括号等。然后再判断是否为base64.
  const urlReg = /url\((['"]?)((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)(\1)\)/g;

  return code.replace(urlReg, (_m, pre, url, post) => {
    const base64Regx = /^data:/;
    const isBase64 = base64Regx.test(url);

    /** 如果匹配到data:前缀,则认为是base64文件,直接不进行路径替换吧 */
    if (isBase64) {
      return _m;
    }

    return `url(${pre}${getAbsolutePath(url, baseUrl)}${post})`
  })
  • 正则图解

https://ihateregex.io/playground/

image

@yiludege
Copy link
Collaborator

感谢贡献!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants