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 scoped css #1487

Merged
merged 3 commits into from
Dec 24, 2024
Merged

Fix scoped css #1487

merged 3 commits into from
Dec 24, 2024

Conversation

sea-chao
Copy link

@sea-chao sea-chao commented Dec 24, 2024

Fix #1482

问题描述

子应用为vue3+vite4时,HRM时micro-app scope丢失

问题原因

vite4在进行HMR时,对于SFC中的CSS变化,会直接修改style标签中的内容,但scopedCSS仅在节点插入时被计算

function updateStyle(id, content) {
  let style = sheetsMap.get(id);
  if (!style) {
    style = document.createElement("style");
    style.setAttribute("type", "text/css");
    style.setAttribute("data-vite-dev-id", id);
    style.textContent = content;
    if (cspNonce) {
      style.setAttribute("nonce", cspNonce);
    }
    if (!lastInsertedStyle) {
      document.head.appendChild(style);
      setTimeout(() => {
        lastInsertedStyle = void 0;
      }, 0);
    } else {
      lastInsertedStyle.insertAdjacentElement("afterend", style);
    }
    lastInsertedStyle = style;
  } else {
    style.textContent = content;
  }
  sheetsMap.set(id, style);
}

解决方法

对于创建了scopedCSS的style标签,监听其内容变化,若变化后不包含scope,则重新计算scope

      const observer = new MutationObserver(() => {
        const isPrefixed = styleElement.textContent && new RegExp(prefix).test(styleElement.textContent)
        observer.disconnect()
        if (!isPrefixed) {
          styleElement.__MICRO_APP_HAS_SCOPED__ = false
        }
        scopedCSS(styleElement, app, linkPath)
      })
      observer.observe(styleElement, { childList: true, characterData: true })

@sea-chao sea-chao merged commit 89e3a9b into dev Dec 24, 2024
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