feng xiaohan

vite 的 css 预处理

css 的预处理器主要是用于配置 css 的预处理语言的语法,比如 less,sass,stylus 等。

preprocessorOptions

通过该项来配置预处理器,该项其实会调用预处理语言(less,sass 等)的内置编译器(lessc、sassc 等)。

补充:
当没有使用任何构建工具的时候如何将预处理语言文件转换为 css 文件?(以 less 为例子)

  1. 安装 less
npm install less -g

注意:全局安装 less 就可以获得 lessc 编译工具,可直接通过 lessc 命令来编译 less 文件。如果本地安装则可以通过npx lessc来编译。

  1. 编译 less 文件
lessc src/index.less src/index.css

指定参数:

lessc src/index.less src/index.css -m=always

这样就会在指定位置生成一个编译后的 css 文件。

vite 中配置预处理器

  • 安装好对应的预处理语言依赖后,在 vite 中配置:
export default defineConfig({
  css: {
    preprocessorOptions: {
      less: {
        math: "always",
      },
    },
  },
});
  • .vue文件中直接使用 less:
<style scoped lang="less">
.test {
  height: 10 * 2vh;
  width: 1920 / 108vh;
  border: 1px solid rgb(77, 73, 73);
  color: yellowgreen;
}
</style>

设置全局变量

在 less 中定义了某个全局变量后,可以直接在想使用的地方引入这个文件然后使用:

// global.less
@textColor: rgb(43, 153, 226);
<style scoped lang="less">
@import "./assets/global.less"; // 注意要加上 ;

.test {
  height: 10 * 2vh;
  width: 1920 / 108vh;
  border: 1px solid rgb(77, 73, 73);
  color: @textColor;
}
</style>

如果不想直接引入这个文件,可以在 vite.config.js 的 preprocessOptions 定义全局变量:

export default defineConfig({
  css: {
    preprocessorOptions: {
      less: {
        math: "always",
        globalVars: {
          textColor: "rgb(43, 153, 226)",
        },
      },
    },
  },
});
<style scoped lang="less">
.test {
  height: 10 * 2vh;
  width: 1920 / 108vh;
  border: 1px solid rgb(77, 73, 73);
  color: @textColor;
}
</style>