How to use css more elegantly in vite

vite's default support for css

In webpack, we need to install it in the project css-loaderto allow webpack to recognize css files.

vue-cliBased on webpack, built in thisloader

Vite inherently supports direct processing of CSS files.

Let's look at an example:

We create index.html, main.js, index.css in the project root directory and install vite

In index.html we introduce main.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
  </head>
  <body>
    <script src="./main.js" type="module"></script>
    <div>Vite天生就是支持对CSS文件的直接处理的。</div>
  </body>
</html>

In main.js we introduce index.css

import "./index.css"

Then, in index.css we add a global background

html,body {
  background: red;
  height: 100%;
  width: 100%;
}

Use vite to start the project, and you can find that the .css file can be recognized without installing any plug-ins.

The principle of adding css style in vite

When vite reads the referenced in main.js index.css, it will use node's fs module to get its content.

First, replace its original content with a js script (to facilitate hot update or css modularization), and set it Content-Typeto js at the same time, so that the browser can execute the file with the css suffix in the form of a JS script.

Then, directly create a style tag, and copy the original content in the index.css file directly into the style tag. Finally, insert the style tag into index.html head.

CssModule

The above method of importing style files is flawed. For example, if two .css files define the same class name, the style will be overwritten.

Note that we are talking about developing the project without using any scaffolding or front-end framework. If you use vue to develop a project, the scope attribute of its tag can also solve this problem.

//  index.css
.wrap{
 background: yellow;
}
// test.css
.wrap{
 background: yellow;
}
// main.js
import "./moduleA.js";
import "./moduleB.js";

// moduleA.js
import "./index.css";
const div = document.createElement("div")
document.body.appendChild(div)
div.className = "footer"
div.innerText ="别看我只是一只羊"

// moduleB.js
import "./test.css";
const div = document.createElement("div")
document.body.appendChild(div)
div.className = "footer"
div.innerText ="羊儿的聪明难以想象!"

index.html

<!DOCTYPE html>
<html lang="en">
  <body>
    <script src="./main.js" type="module"></script>
  </body>
</html>

Apparently, the styles in test.css override the styles in index.css.

If a project is developed by multiple people, it is very common to have duplicate class names, but the above problems will obviously bring trouble to our project development.

Therefore, vite solves this problem with the help of CssModule.

What is CssModule: https://www.ruanyifeng.com/blog/2016/06/css_modules.html

CSS rules are global, and the style rules of any component are valid for the entire page.

The only way to generate a local scope is to use a unique class name that will not have the same name as other selectors. This is what CSS Modules do.

use

To solve this problem with the help of CssModule, we only need to name the file in the way of xxx.module.css.

We change index.css to index.module.css and test.css to test.module.css

Then, moduleA.js and moduleB.js are slightly adjusted

// moduleA.js
import index from "./index.module.css";
const div = document.createElement("div")
document.body.appendChild(div)
div.className = index.wrap
div.innerText ="别看我只是一只羊"

// moduleB.js
import test from "./test.module.css";
const div = document.createElement("div");
document.body.appendChild(div);
div.className = test.wrap;
div.innerText = "羊儿的聪明难以想象";

Note: For the imported style file, we can print the console.log(index):

It will be found that after css is replaced with js, the exported object contains an object of the original class name and the modified class name.

Therefore, we can get the modified class name by div.className = test.wrap.

After the modification, you can see that the style problem has been resolved.

vite configure CSS

modules option

Through the css.modules configuration item of vite.config.js, we can change some default content of CssModule, such as enabling or disabling its function, changing its hash name, etc.

import { defineConfig } from "vite";
export default defineConfig( {
  // 对css的行为进行配置
  css:{
    // 是对css模块化的默认行为进行覆盖
    modules:{
      
    }
  }
});

The configuration of modules will actually be passed to postcss to help it handle it, so for specific configuration, you can refer to: postcss-modules .

Complete configuration of the modules option

modules: {
  // 是否开启模块化
  scopeBehaviour: 'global' | 'local'
  // 代表你不想参与到css模块化的路径
  globalModulePaths: RegExp[]
  // 更改生成的哈希名称,一个字符串模板或者通过函数返回
  generateScopedName:
    | string
    | ((name: string, filename: string, css: string) => string)
  // 生成hash名称的前缀
  hashPrefix: string
  // 修改生成的配置对象的key的展示形式(驼峰还是中划线形式)
  localsConvention:
    | 'camelCase'
    | 'camelCaseOnly'
    | 'dashes'
    | 'dashesOnly'
    | null
}

scopeBehaviour

Suggestion for configuration: If you have a bad brain, you can change it

Whether to enable the modularization function.

  • Optional arguments: 'global' | 'local'
  • Default: 'local'

We change the default value to global

import { defineConfig } from "vite";
export default defineConfig({
  css: {
    // 是对css模块化的默认行为进行覆盖
    modules: {
      scopeBehaviour: "global" 
    }
  }
});

It can be found that the modular function is turned off.

localsConvention

Returns the format of the key-value pair

Default: camelCaseOnly

optional parameters

  • camelCase
  • camelCaseOnly
  • dashes
  • dashesOnly
  • null

Let's configure it as camelCase to try

import { defineConfig } from "vite";
export default defineConfig({
  css: {
    // 是对css模块化的默认行为进行覆盖
    modules: {
      localsConvention: "camelCase", 
      scopeBehaviour: "local" 
    }
  }
});
// index.module.css
.table-wrap{
 background: yellow;
}
// moduleA.js
import index from "./index.module.css";
console.log('index: ', index);

It can be found that when referencing styles, use ele.className = index[camel case naming], ele.className = index[dash naming] can be used.

camelCaseOnly

null

dashes

dashesOnly

Guess you like

Origin blog.csdn.net/weixin_46769087/article/details/128286290