问题:本地环境换肤可以,但是打包后发现自己写的主题色值#409eff,并没有被替换成功,只有element ui自身的主题色替换了
主要代码如下:
//watch监听主题色变化
theme: {
async handler(val) {
const oldVal = this.chalk ? this.theme : ORIGINAL_THEME
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
const $message = this.$message({
message: '主题色切换中...',
customClass: 'theme-message',
type: 'success',
duration: 0,
iconClass: 'el-icon-loading',
})
const getHandler = (variable, id) => {
return () => {
const originalCluster = this.getThemeCluster(
ORIGINAL_THEME.replace('#', '')
)
const newStyle = this.updateStyle(
this[variable],
originalCluster,
themeCluster
)
let styleTag = document.getElementById(id)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.setAttribute('id', id)
document.head.appendChild(styleTag)
}
styleTag.innerText = newStyle
}
}
if (!this.chalk) {
const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
await this.getCSSString(url, 'chalk')
}
const chalkHandler = getHandler('chalk', 'chalk-style')
chalkHandler()
/**++++++++++++++++++++++++++++++++++++++++++++++++ */
//为解决生产环境中切换主题色失败
if (!this.flag && process.env.NODE_ENV === 'production') {
//判断是否是第一次打开页面
this.flag = true
;[].slice
.call(document.querySelectorAll('link')) //获取所有的link链接
.forEach(async (item) => {
if (item.rel === 'stylesheet' || item.as === 'style') {
//判断是否是 css
const { data } = await axios.get(item.href) // 重新获取到 css 的内容
if (
new RegExp(oldVal, 'i').test(data) && // 判断是否需要换肤
!/Chalk Variables/.test(data) // 判断是否是 element-ui 的 css 前面已经进行处理了这里忽略
) {
item.remove() // 移出 link
const style = document.createElement('style') // 创建 style
style.innerText = data // 把 link 的内容添加到 style 标签中
// 更新背景图会导致路径错误,忽略更新。
style.innerText = data.replace(
/url\(..\/..\/static/g,
'url(static'
)
style.isAdd = true // 为后面判断是否是 link 生成的style,方便标识加入到头部head中
styles.push(style)
this.stylesRender(styles, originalCluster, themeCluster) // 样式渲染
}
}
})
}
/**++++++++++++++++++++++++++++++++++++++++++++++++ */
// 筛选需要修改的style
const styles = [].slice
.call(document.querySelectorAll('style'))
.filter((style) => {
const text = style.innerText
return (
new RegExp(oldVal, 'i').test(text) &&
!/Chalk Variables/.test(text)
)
})
this.styleRender(styles, originalCluster, themeCluster)
this.$emit('change', val)
$message.close()
},
immediate: true,
},
// 遍历修改所有需修改的style
styleRender(styles, originalCluster, themeCluster) {
styles.forEach((style) => {
const { innerText } = style
if (typeof innerText !== 'string') return
style.innerText = this.updateStyle(
innerText,
originalCluster,
themeCluster
)
//打包后的link转换的style
if (style.isAdd) {
// 如果是通过 link 创建的style 就添加到head中
style.isAdd = false
document.head.appendChild(style)
}
})
},
//更新