vite注意事项

vite本地开发第三方库样式冲突解决方案

问题描述

在使用vite开发vue项目时,
同时使用了 elementui-plus和 element-plus-x,
然后 在开发环境 里面有一些 element-plus-x 的特殊样式会污染elementui-plus的原有样式。

比如 ThoughtChain 这个思维链的组件 用了 el-collapse ,然后修改了他的样式的高度 height
elementui-plus的原样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.el-collapse-item__header {
width: 100%;
padding: 0;
border: none;
display: flex;
align-items: center;
min-height: var(--el-collapse-header-height);
line-height: var(--el-collapse-header-height);
background-color: var(--el-collapse-header-bg-color);
color: var(--el-collapse-header-text-color);
cursor: pointer;
border-bottom: 1px solid var(--el-collapse-border-color);
font-size: var(--el-collapse-header-font-size);
font-weight: 500;
transition: border-bottom-color var(--el-transition-duration);
outline: none;
}

修改后 多了一个固定高度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#elx_wrapper .el-collapse-item__header {
align-items: center;
background-color: var(--el-collapse-header-bg-color);
border: none;
border-bottom: 1px solid var(--el-collapse-border-color);
color: var(--el-collapse-header-text-color);
cursor: pointer;
display: flex;
font-size: var(--el-collapse-header-font-size);
font-weight: 500;
height: var(--el-collapse-header-height); //这一行 上面是没有的。
line-height: var(--el-collapse-header-height);
outline: none;
padding: 0;
transition: border-bottom-color var(--el-transition-duration);
width: 100%;
}

上面只是个比喻

解决方案

也是考虑了好几种方案。但是都感觉对已有项目的改动太大。

  • 方案一:
    用element-plus的 el-config-provider 包裹,然后修改namespace为ep。全局修改element-plus的样式浅醉
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<el-config-provider namespace="ep">
<!-- ... -->
</el-config-provider>

写一个 css styles/element/index.scss
@forward 'element-plus/theme-chalk/src/mixins/config.scss' with (
$namespace: 'ep'
);

在 vite.config.ts 中导入 styles/element/index.scss

import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
// ...
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "~/styles/element/index.scss" as *;`,
},
},
},
// ...
})
  • 方案二: 使用posscss插件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
在vite.config.ts中配置
import prefixSelector from 'postcss-prefix-selector'
css: {
preprocessorOptions: {
// 定义全局 SCSS 变量
scss: {
additionalData: `@use "@/styles/variables.scss" as *;`,
},
},
postcss: {
plugins: [
prefixSelector({
// 只有当处理 element-plus-x 的样式文件时才生效
// 注意:你需要确认该库样式文件的具体路径特征
includeFiles: [/element-plus-x/, /node_modules\/element-plus-x/],

// 忽略 html 和 body 标签,避免破坏全局基础样式
exclude: ['html', 'body', ':root'],

// 核心:将所有样式限制在这个 ID 下
prefix: '#elx_wrapper',

transform(prefix: string, selector: string, prefixedSelector: string, filePath: string) {
// 对于 :root 下的变量定义,可能需要特殊处理以免丢失
if (selector === ':root') {
return ':root #elx_wrapper'
}
return prefixedSelector
}
})
]
}

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器