Vite笔记之10-vite配置文件css(preprocessorOptions)

3,324 阅读3分钟

1. preprocessorOptions配置作用

主要用来配置css预处理器的一些全局参数,更多的参数参考 less官网。如果没有使用构建工具,又使用less假设没有使用构建工具, 我们又想去编译less文件的话,就需要安装对应的编译器。

例如:

yarn add less    # lessc的编译器
  • 你只要安装了node, 你就可以使用node index.js
  • 你只要安装了less 你就可以使用lessc去编译less文件 —- npx lessc index.css

index.css:不使用always不会进行计算,只会管width 括号中的

html {
    width:(100px / 2);
    height:100px / 2
}

less是可以定义全局变量的:

varible.less

@color: blue;

index.module.less

@import url("./varible.less");

.content {
  .main {
    background-color: @color;
  }
}

main.js

import "./index.module.less"

image.png

问题: 每次都需要进行import 导入,可以在全局中定义

preprocessorOptions: {
    less: {
        math: "always",
        globalVars: {
            mainColor:'red'
        }
    },

index.module.less

直接使用@mainColor
.content {
  .main {
    background-color: @mainColor;
  }
}

image.png

2.sourceMap使用

sourceMap是什么,是文件之间的索引:

假设我们的代码被压缩或者被编译过了, 这个时候假设程序出错, 他将不会产生正确的错误位置信息 如果设置了sourceMap, 他就会有一个索引文件map,sourceMap解决的问题极其的微小, 但是他的实现过程非常的复杂。

开启后,会出现css的映射,例如:

image.png

image.png

3.postcss

保证css在执行起来是万无一失的,是像babel一样的工具。

:root {
    --globalColor: lightblue;
}
// 使用
var(--globalColor)

chrome使用:可以正常解析 ——> postcss ——> 直接变成lightblue

image.png

浏览器的兼容性你能考虑到吗, 低版本的兼容性问题,预处理器并不能够解决这些问题:

  1. 对未来css属性的一些使用降级问题
  2. 前缀补全: Google非常卷 --webkit,预处理器不能添加补全

都对postcss有一个误区: 他们认为postcss和less sass是差不多级别

我们写的css代码 --> postcss ---> less --> 再次对未来的高级css语法进行降级 --> 前缀补全 --> 浏览器客户端

目前来说 less和sass等一系列预处理器的postcss插件已经停止维护了 less插件,如果每次sass、less语法更新postcss-less/postcss-sass插件也需要更新,没有必要。 你自己去用less和sass编译完了, 然后你把编译结果给我

所以业内就产生了一个新的说法: postcss是后处理器 ,大于less和sass, 如果直接处理less的postcss的插件也就ok了

babel

babel --> 帮助我们让js执行起来万无一失

我们写的js代码(怎么爽怎么来) --> babel --> 将最新的ts语法进行转换js语法 --> 做一次语法降级 --> 浏览器客户端去执行

class App {} // es6的写法

function App() {} // es3的语法

4.postcss的使用

  1. 安装依赖
yarn add postcss postcss-cli -D
// cli 是命令行终端命令 postcss
// 编译
npx postcss index.css -o result.css
  1. 书写描述文件

    postcss.config.js 运行时会读取配置文件

    插件 github.com/postcss/pos…

// 就类似于全屋净水系统的加插槽
// 预设环境里面是会包含很多的插件
// 语法降级 --> postcss-low-level
// 编译插件 --> postcss-compiler
// ...
const postcssPresetEnv = require("postcss-preset-env");

// 预设就是帮你一次性的把这些必要的插件都给你装上了
// 做语法的编译 less语法 sass语法 (语法嵌套 函数 变量) postcss的插件 --> 
module.exports = {
    plugins: [postcssPresetEnv(/* pluginOptions */)]
}
:root{
	--globalColor:lightblue;
}

div{
	background-color: var(--globalColor);
}

//npx postcss index.css -o result.css

:root{
	--globalColor:lightblue;
}

div{
    background-color: lightblue; // 多添加了这一行 
    background-color: var(--globalColor);
}