美文网首页
vue3 在 vite 构建的vue3项目中使用 scss和le

vue3 在 vite 构建的vue3项目中使用 scss和le

作者: 暴躁程序员 | 来源:发表于2023-04-06 18:41 被阅读0次
  1. 在 vue3 中 sass、less 安装后既可使用
  2. 但是定义全局样式需要在 vite.config.js 中配置,不可在main.js中引入sass、less文件(可以在引入css文件)

一、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>

相关文章

网友评论

      本文标题:vue3 在 vite 构建的vue3项目中使用 scss和le

      本文链接:https://www.haomeiwen.com/subject/aemuddtx.html