前端 vite中对css及css模块化的处理 - moduule

📅 2026-12-01 👤 拼多多助力营销技巧 📂 拼多多助力2027 👁️ 115 次阅读

目录

vite中对css及css模块化的简单处理

vite配置中css配置流程(modules)

vite配置文件中css配置流程(preprocessorOptions)

vite配置文件中css配置流程(devSourcemap)

postcss

使用css

vite配置文件中css配置流程(postcss)

为什么postcss没有编译全局css变量

vite中对css及css模块化的简单处理

vite天生就支持对css文件的直接处理

//index.css

html,body{

width:100%;

height:100%;

background:red;

}

//main.js

import './index.css'

import './componentA.js'

import './componentB.js'//css类型重复componentA样式被覆盖

//componentA.js

import './componentA.css'

const div=document.createElement('div')

div.className='footer'

document.body.appendChild(div)

//componentA.css

.footer{

width:100px;

height: 200px;

background-color: aquamarine;

}

//componentB.js

import './componentB.css'

const div=document.createElement('div')

div.className='footer'

document.body.appendChild(div)

//componentB.css

.footer{

width: 200px;

height: 200px;

background-color: black;

}

vite在读取到main.js中引用到了Index.cs直接去使用fs模块去读取index.css中文件内容直接创建一个style标签,将index.css中文件内容直接copy进style标签里将style标签插入到index.html的head中将该css文件中的内容直接替换为js脚本(方便热更新或者css模块化),从而让浏览器以JS脚本的形式来执行该csshh后缀的文件

解决重复类名样式覆盖——csssmodule

//componentA.module.css

.footer{

width:100px;

height: 200px;

background-color: aquamarine;

}

//componentB.module.css

.footer{

width: 200px;

height: 200px;

background-color: black;

}

//componentA.js

import componentACss from './componentA.module.css'

console.log('componentACss',componentACss)

```

```

div.className=componentACss.footer

//componentB.js

import componentBCss from './componentB.module.css'

console.log('componentBCss',componentBCss )

```

```

div.className=componentBCss.footer

css模块化流程:

module.css (module是一种约定,表示需要开启css模块化)他会将你的所有类名进行一定规则的替换(将footer替换成_footer_i22st_1 )同时创建一个映射对象{ footer: "_footer_i22st_1"}将替换过后的内容塞进style标签里然后放入到head标签中(能够读到index.html的文件内容)将componentA.module.css内容进行全部抹除,替换成JS脚本将创建的映射对象在脚本中进行默认导出

预处理器(less,scss…) :给我们提供了一些方便且非常实用的方法

//index.module.less

.content{

.main{

background:green;

}

}

//componentA.js

import componentALess from './index.module.less'

```

```

console.log(componentALess )

vite配置中css配置流程(modules)

在vite.config.js中我们通过css属性去控制整个vite对于css的处理行为

localConvention 修改生成的配置对象的key的展示形式(驼峰还是中划线形式)

camelcase 配置转换类名camelCaseOnly 只展示驼峰式dashesOnly 只显示含-的类名属性(默认值)

//componentA.module.css

```

```

.footer-content{

width:200px;

height:200px;

background:yellow;

}

//componentA.js

```

```

console.log ("componentACss",componentACss,componentALess);

div.className=componentACss.footerContent;

//componentACss对象下,footer-content:'_footer-content_kfrq8_7'

/*localConvention:

"camelcase"--componentACss对象多了一个 footerContent:'_footer-content_kfrq8_7'

"camelCaseOnly"--componentACss对象对于.footer-content只有一个 footerContent:'_footer-content_kfrq8_7'

"dashesOnly"--默认值,.footer-content类只显示footer-content:'_footer-content_kfrq8_7'

*/

scopeBehaviour 配置当前的模块化行为是模块化还是全局化(有hash就是开启了模块化的一个标志,因为他可以保证产生不同的hash值来控制样式类名不被覆盖)

local 默认值 开启模块化global 关闭模块化,模块化样式消失generateScopedName 生成的类名名字的规则(定义类名的展示格式)

可以配置为函数也可以配置成字符串规则(github.com/webpack/loader-utils#interpolatename)

//generateScopedName: "[name]_[local]_[hash:5]"---->local即是footer-content hashPrefix 给hash补的前缀

生成hash会根据你的类名+一些其他的字符串 (文件名+内部随机生成的字符串)去进行生成,如果你想要你生成hash更加的独特一点,你可以配置hashPrefix,你配置的这个字符串会,参与到最终的hash生成。(hash:只要你的字符串有一个字不一样,那么生成的hash就完全不一样,但是只要你的字符串完全一样,生成的hash就会一样)

globalModulePaths: [] // 代表你不想参与到css模块化的路径

引入第三方库是不希望类名产生hash变化。

//vite.config.js

import { defineConfig } from "vite" ;

export default defineConfig ({

optimizeDeps: {

exclude: [],//将指定数组中的依赖不进行依赖预构建

},

envPrefix: "ENV_",

css: {//对css行为进行配置

//modules配置最终会交给postcss modules

modules:{//是对css模块化的默认行为进行覆盖

localConvention:"camelcase",//修改生成的配置对象的key的展示形式(驼峰还是中划线形式)

scopeBehaviour:'local',//配置当前的模块化行为是模块化还是全局化(有hash就是开启了模块化的一个标志,因为他可以保证产生不同的hash值来控制样式类名不被覆盖)

//generateScopedName: "[name]_[local]_[hash:5]" //github.com/webpack/loader-utils#interpolatename

generateScopedName:( name,filename,css)=>{

//配置成函数以后,返回值就决定了他最终显示的类型

//return '123'//所有类名都变为123

//name:代表的是你此刻css文件中的类名

//fileName:是你当前css文件的绝对路径

//css:是你当前样式

console.log(name,filename,css)//输出在node

return `${name}_${Math.random().toString(36).substr(3,8)}`

},

hashPrefix:'hello'//将hello打散放在hash中

globalModulePaths: ['./componentB.moduule.css'], // 代表你不想参与到css模块化的路径

}

}

});

vite配置文件中css配置流程(preprocessorOptions)

preprocessorOptions:主要是用来配置css预处理的一些全局参数(命令行参数)

math globalVars全局变量

//index.module.less

//@mainColor:'red'

//import url(./variables.less)

.content{

.main{

background:green;

padding:(100px / 2);//50px

margin:100px / 2;//npx lessc --math="always index.module.less时:50px

//npx lessc index.module.less时:50px时:100px / 2,默认只数学处理括号内的表达式

background:@mainColor;

}

}

//variables.less

//@mainColor:'red'

//全局变量可以在globalVars里设置避免重复import造成性能问题

//vue.base.config.js

import { defineConfig } from "vite" ;

export default defineConfig ({

optimizeDeps: {

exclude: [],//将指定数组中的依赖不进行依赖预构建

},

envPrefix: "ENV_",

css: {

modules:{

```

```

},

preprocessorOptions:{ //key + config key代表预处理器名

less:{ //整个的配置对象都会最终给到less的执行参数(全局参数)中去

//在webpack里就给less-loader去配置就好了

math:'always',

globalVars:{//定义全局变量

mainColor:'red',

}

},

sass:{},

}

}

});

vite配置文件中css配置流程(devSourcemap)

devSourcemap文件之间的索引

假设我们的代码被压缩或者被编译过了,这个时候假设程序出错,他将不会产生正确的错误位置信息。如果设置了sourceMap,他就会有一个索引文件

import { defineConfig } from "vite" ;

export default defineConfig ({

optimizeDeps: {

exclude: [],//将指定数组中的依赖不进行依赖预构建

},

envPrefix: "ENV_",

css: {

modules:{

```

```

},

preprocessorOptions:{

```

```

},

devSourcemap:true//默认为false

}

});

postcss

vite对postcss有良好的支持

//main.js

import './index.less'

//index.less

:root{

// css新提案:css变量

--globalColor:lightblue; 拼多多帮助力入口

}

//componentA.modules.css

.footer-content{

width:200px;

height: 200px;

background-color: var(--globalColor);

}

对于浏览器的兼容性,以下问题预处理器不能解决:

对未来css属性的一些使用降级问题前缀补全:如:Google自动补全--webkit前缀

postcss作用流程:完成css编写 -->postcss【去将语法进行编译(嵌套语法,函数,变量)成原生css】 less sass等预处理器都可以做 -->再次对未来的高级css语法进行降级 -- >前缀补全 -->浏览器客户端

使用css

安装依赖

yarn add postcss-cli -D

yarn add postcss -D

书写描述文件

//index.css

:root{

// css新提案:css变量

--globalColor:lightblue;

}

div{

background-color: var(--globalColor);

}

//终端https://www.npmjs.com/package/postcss-cli

npx postcss index.css -o result.css

//index.css中出现压缩后的css内容

//postcss.config.js postcss配置文件格式

const postcssPresetEnv=require('postcss-preset-env')

module.exports={

// yarn add postcss-preset-env -D 预设环境

plugins:[postcssPresetEnv(/* pluginOptions */)],

}

预设环境里面是会包含很多的插件

语法降级:postcss-low- leve

npx postcss index.css -o result.css语法编译 less语法、sass语法 (语法 嵌套 函数变量)postcss的插件 div{

background:lightblue;

background:var(--globalColor);

}

编译插件:postcss-compile

vite配置文件中css配置流程(postcss)

直接在css.postcss中进行配置,该属性直接配置的就是postcss的配置

postcss-preset-env:支持css变量和一些未来css语法自动补全(autoprefixer)

//vite.base.config.js

import { defineConfig } from "vite" ;

//const postcsspresetEn = require("postcss-preset-env")

//vite会自动读取postcss.config.js文件

export default defineConfig ({

optimizeDeps: {

exclude: [],//将指定数组中的依赖不进行依赖预构建

},

envPrefix: "ENV_",

css: {//对css行为进行配置

//modules配置最终会交给postcss modules

modules:{//是对css模块化的默认行为进行覆盖

```

```

},

preprocessorOptions:{

```

```

},

devSourcemap:true,//默认为false

// postcss:{

// plugins:[postcsspresetEn()],

// },

}

});

//index.less

.content{

width: 400px;

.main{

background: green;

padding: (100px / 2);

margin: 100px / 2;

background-color: red;

filter: blur(100px);

// 响应式布局,左侧一个菜单栏宽度自适应根据屏幕 30% 最小宽度100px 最大宽度200px

// 父容器: 400px 200px 800px

// 自身: 120px 60->100px 240->200px

// preset-env会帮我们做语法降级:width:max(100px,min(30%,200px))

// preset-env内部会有一个主流浏览器的支持表

width: clamp(100px,30%,200px);

user-select: none;

//自动补全 -webkit-user-select: none; -moz-user-select: none;

}

}

为什么postcss没有编译全局css变量

解析完index.less文件就结束了,当在componentA.module.css文件中使用变量时重新开始解析,对于之前的全局变量没有存储。

//varible.css 全局变量一般使用.css文件

/*

我们使用的一些未来的css特性是不需要经过less sass的预处理器进行编译,我们只能交给postcss去处理

*/

:root{

--globalColor:lightblue;

}

//main.js

import './varible.css'

//postcss.config.js

const postcssPresetEnv=require('postcss-preset-env')

const path = require("path")//文件路径补全

module.exports={

plugins:[

postcssPresetEnv({

importFrom: path.resolve(__dirname,'./varible.css') //优先导入,postcss记住变量

})

],

}

好文链接,前端

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧