feng xiaohan

vite 中使用 css

vite 直接就支持 css 文件,不需要别的操作。

原理

当 vite 在读取到 main.js 中引用的 index.css 时:

  1. 首先使用 node 的 fs 模块获取 css 文件的内容。
    浏览器行为:
    在浏览器获取 css 文件时,vite 会将其原本的 css 内容替换为 js 脚本,并让浏览器以执行 js 文件的形式来执行 css 后缀的文件。该脚本的内容执行内容如下:

    细节:获取到内容后,会见文件在本地的绝对路径作为 id 和内容一起传给 vite 处理 css 的函数 ——— updateStyle(id, content),该函数会创建一个 style 标签,并将 type 设置为 ‘text/css’,将其插入到 head 中(后面的内容)。

  2. 创建一个 style 标签,将 css 文件中的内容直接复制到里面。

  3. style 标签插入到 head 中。

CSS Module

问题:如果两个 css 文件定义了同一个类名,样式会被覆盖。
解决:使用 CSS Module(postcss),将每一个 class 名变为独一无二的,不会与其他选择器重名。

将 css 文件的后缀改为 .module.css 即可。vite 会利用 postcss 自动将后缀名为 .module.css 的文件转换为 CSS Module,在类名前添加上独一无二的 hash 值。

使用:

import index from './css/test2.module.css'
...
div.className = index.test

引入的值可以是认为原始 css 类名 和修改后独一无二的 css 类名 的映射表。

配置 CSS Module

可以通过 vite.config.js 配置 CSS Module,其实也是将参数传递给 postcss。

export default defineConfig({
  // css module
  css: {
    // (postcss)
    modules: {
      scopeBehaviour: "local", // 是否开启模块化 local(*) | global
      localsConvention: "camelCaseOnly", // 返回键值对格式 camelCaseOnly(*) | camelCase | dashes | dashesOnly | null
      // 修改生成的 hash 名称
      // generateScopedName: '[name]-[local]-[hash:base64:5]', // string

      // hashPrefix: 'prefix-', // 生成的 hash 名前缀 ?
      globalModulePaths: ["src/module/cssNoUseModule/*.*.css"], // 不想使用css module的路径 RegExp[]
    },
  },
});

CSS sourcemap

默认情况下,我们在开发环境调试定位元素时,指向的是 head 里的 style 标签。在开发环境下,vite 可以配置 css 的 sourcemap 属性devSourcemap,可以让我们找到处理后 css 类所对应的源文件。

export default defineConfig({
  css: {
    // modules: {
    //   // ...
    // },
    // preprocessorOptions: {
    //   // ...
    // }
    devSourcemap: true,
  },
});