如何在vuejs3/vite中使用sass

blu*_*ade 34 vuejs3 vite

我从 vite / vuejs 3 开始

使用 npm install -D sass 安装 sass 后,我尝试将我的 _variables.js 文件添加到 vite.config.js

css: {preprocessorOptions: {scss: {additionalData: `@import" ./src/css/_variables.scss ";`,},},},
Run Code Online (Sandbox Code Playgroud)

不工作!

它也适用于 vue.config

css: {
     loaderOptions: {
       sass: {
         sassOptions: {
            prependData: `@import" @ / css / _variables.scss ";`,
         }
       }
     }
   },
Run Code Online (Sandbox Code Playgroud)

之后尝试在 main.js import "./css/_variables.scss" 中导入文件

不幸的是,我的组件找不到变量,错误在哪里

And*_*par 47

Vite 有点不同

    import { defineConfig } from 'vite'
    
    export default defineConfig({
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `
              @import "./src/styles/_animations.scss";
              @import "./src/styles/_variables.scss";
              @import "./src/styles/_mixins.scss";
              @import "./src/styles/_helpers.scss";
            `
          }
        }
      }
    })
Run Code Online (Sandbox Code Playgroud)


wit*_*ein 29

这是我的工作设置,从vite 文档和命令中获取yarn add -D sass

// package.json
{
  "dependencies": {
   ...
    "vue": "^3.0.5"
  },
  "devDependencies": {
    ...
    "sass": "^1.32.11",
    "vite": "^2.2.3"
  }
}
Run Code Online (Sandbox Code Playgroud)
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()]
})
Run Code Online (Sandbox Code Playgroud)
// App.vue
<template>...</template>
<script>...</script>

<style lang="scss">
@import "./assets/style.scss";
</style>
Run Code Online (Sandbox Code Playgroud)
// style.scss
[data-theme="dark"] {
  --bg-color1: #121416;
  --font-color: #f4f4f4;
}
[data-theme="light"] {
  --bg-color1: #f4f4f4;
  --font-color: #121416;
}
...
body {
  background-color: var(--bg-color1);
  color: var(--font-color);
}

Run Code Online (Sandbox Code Playgroud)

我的vue.config.js很干净——没什么特别的。

  • 您是否尝试过在“main.js”中导入您的 scss 文件?对我来说,可以通过“./”导入多个 scss 文件。 (2认同)

小智 15

对于Vue3,如文档中所述:https://vitejs.dev/guide/features.html#css-pre-processors

您只需要添加

npm add -D sass
Run Code Online (Sandbox Code Playgroud)

并在脚本标签中使用

<style lang="scss">
// OR
<style lang="sass">
Run Code Online (Sandbox Code Playgroud)

  • 记得再次运行命令“npm run dev”才能生效。 (2认同)

Jor*_*ñan 6

我的问题如下:我无法在其中获取 scss 变量<style lang="scss">,现在这是我的良好配置:

// vite.config.ts

export default defineConfig({
  plugins: [
    vue(),
    ...
  ],
  ...,
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: ` // just variables loaded globally
          @import "./src/assets/styles/setup/fonts";
          @import "./src/assets/styles/setup/colors";
          @import "./src/assets/styles/setup/mixins";
        `
      }
    }
  }
});

// App.vue

<style lang="scss"> // the main file that imports everything related with styles
@import "@/assets/styles/main.scss";
</style>
Run Code Online (Sandbox Code Playgroud)