開啟了 strictStyleIsolation: true樣式隔離后會導致圖標消失
如下:
image.png
原因就是字體圖標沒有被正確加載到
解決辦法:
在afterMount生命周期中查找所有的style,如果里面包含字體樣式的引入就插入到主應用的head里面,確保加載字體圖標文件
async afterMount(app, global) {
const shadowRoot = document.querySelector(`[data-name="${app.name}"]`)?.shadowRoot
if (shadowRoot) {
shadowRoot.querySelectorAll('style').forEach(stl => {
if (stl.textContent && /\.woff/.test(stl.textContent)) {
// 使用正則匹配所有的 @font-face 規則
const fontFaceMatches = [...stl.textContent.matchAll(/@font-face\s*\{([^}]+)\}/g)]
fontFaceMatches.forEach(fontFaceMatch => {
// 提取每個 @font-face 規則中的 font-family 屬性
const fontFamilyMatch = fontFaceMatch[0].match(/font-family:(.*?);/)
if (fontFamilyMatch && fontFamilyMatch[1]) {
const fontFamily = fontFamilyMatch[1].replace(/['"\s]/g, '')
const styleContent = fontFaceMatch[0].replace(/(\.\.\/)+/g, entry) // 替換入口路徑,
// 檢查 head 中是否已存在該 font-family 的 @font-face 樣式
const existingStyle = document.head.querySelector(`style[data-font-family="${fontFamily}"]`)
if (!existingStyle) {
// 如果沒有找到重復的樣式,則插入新的樣式
const st = document.createElement('style')
st.innerHTML = styleContent
st.setAttribute('data-font-family', fontFamily) // 為 style 元素添加自定義屬性
document.head.appendChild(st)
}
}
})
}
})
}
}