vite-plugin-qiankun icon indicating copy to clipboard operation
vite-plugin-qiankun copied to clipboard

Vite应用会动态载入CSS到Head中,这导致了CSS污染,有什么解决方案吗?

Open baijunjie opened this issue 1 year ago • 1 comments

微应用

  • 子应用A,依赖 Antd v1,采用webpack编译
  • 子应用B,依赖 Antd v3,采用vite + vite-plugin-qiankun编译

现象

  • 子应用A,所有动态载入的资源都在 <qiankun-head> 中,当应用卸载后,这些资源会被同时移除
  • 子应用B,所有动态载入的资源都在 <head> 中,当应用卸载后,这些资源仍然存在

结果 切换到子应用A,子应用B卸载后,Antd v3 的 CSS 仍然存在,并与子应用A中的 Antd v1 的 CSS 发生冲突,导致CSS污染

版本 vite: 4.0.3 vite-plugin-qiankun: 1.0.15 qiankun: 2.8.4

baijunjie avatar Jan 25 '23 03:01 baijunjie

我没有找到很好的决绝方案,包括启用 qiankun 的 strictStyleIsolation: true 或者 experimentalStyleIsolation: true,都会有一些问题,比如 html,body 的 css 会丢失。

最终我做了一下处理,算是暂时解决的我的问题

let headStyles = []

export function mount (app, container) {
  if (headStyles.length) {
    headStyles.forEach(node => {
      document.head.appendChild(node)
    })
    headStyles = []
  }
  ...
}

export function unmount (app) {
  Array.from(document.head.children).forEach(node => {
    if (node.tagName === 'STYLE' || node.rel === 'stylesheet') {
      node.remove()
      headStyles.push(node)
    }
  })
  ...
}

baijunjie avatar Jan 26 '23 05:01 baijunjie