对css的处理
html,
body {
width: 100%;
height: 100%;
background-color: rebeccapurple;
}
import './index.css'
可以看到 vite 天生就支持对 css 文件的直接处理,处理流程大概如下:
-
vite 在 main.js 中读取到引用的 index.css
-
直接使用fs模块读取 index.css 中的内容
-
创建一个style标签,将 index.css 中的内容直接复制到style标签里面
-
将style标签插入到 index.html 的 head 中
-
将该 css 文件中的内容直接替换为js脚本 ( 方便热更新或者css模块化 ),同时设置 Content-type 为 js,从而让浏览器以js脚本的形式来执行该css的后缀的文件
对css模块化的处理
场景:组件取了同样的类名,会导致冲突,如下:
import './componentA.css'
const div = document.createElement('div')
document.body.appendChild(div)
div.className = 'footer-content'
.footer {
width: 200px;
height: 200px;
background-color: beige;
}
.footer-content {
width: 200px;
height: 200px;
background-color: blue;
}
import './componentB.css'
const div = document.createElement('div')
document.body.appendChild(div)
div.className = 'footer-content'
.footer {
width: 200px;
height: 200px;
background-color: beige;
}
.footer-content {
width: 200px;
height: 200px;
background-color: yellow;
}
可以看到后面引入的b的样式已经覆盖掉了A的样式了,所以我们可以开启模块化,只需要将css文件中间加上module关键字就行了,这样就会默认开启模块化
可以看到此时的css已经加上了hash名,所以就不会冲突了。
css模块化的大致原理如下:
- module.css (module是一种约定, 表示需要开启css模块化)
- 他会将你的所有类名进行一定规则的替换(将footer 替换成 _footer_i22st_1)
- 同时创建一个映射对象{ footer: "_footer_i22st_1" }
- 将替换过后的内容塞进style标签里然后放入到head标签中 (能够读到index.html的文件内容)
- 将componentA.module.css内容进行全部抹除, 替换成JS脚本
- 将创建的映射对象在脚本中进行默认导出