vite 在项目中集成 scss 和 less

在 vue3 中 sass、less 安装后既可使用

一、vue3 中集成 scss

1. 安装依赖

npm install sass -D

2. 定义全局样式

  1. 新建 src\assets\base.scss 全局样式文件
$bgColor: #ccc;
  1. 在 vite.config.js 中配置
import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/assets/base.scss";`,
      },
    },
  },
});
  1. 在组件中使用
<template>
  <div class="main">hello world</div>
</template>

<script>
export default {
  setup() {
    return {};
  },
};
</script>

<style lang="scss" scoped>
.main {
  background: $bgColor;
  color: blue;
}
</style>

二、vue3 中集成 less

1. 安装依赖

npm install less -D

2. 定义全局样式

  1. 新建 src\assets\base.less 全局样式文件
@bgColor: #ccc;
  1. 在 vite.config.js 中配置
import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  css: {
    preprocessorOptions: {
      less: {
        additionalData: `@import "@/assets/base.less";`,
      }
    },
  },
});
  1. 在组件中使用
<template>
  <div class="main">hello world</div>
</template>

<script>
export default {
  setup() {
    return {};
  },
};
</script>

<style lang="less" scoped>
.main {
  background: @bgColor;
  color: blue;
}
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容