Using @use 'sass:color' in my Vue.js/Vite app causes variables imported via additionalData to become unusable
P粉478445671
P粉478445671 2023-08-17 14:44:11
0
1
724
<p>I'm using Vue.js with Vitest and sass loader. </p> <p>When I use <code>@use 'sass:color'</code> in an inline scss file or component, it seems to overwrite the <code>vite.config.ts</ The variable of <code>css.preprocessorOptions.scss.additionalData</code> set in the code> file. </p> <p>The problem is reproduced here: https://stackblitz.com/edit/vitejs-vite-nk8yf5?file=src/style/sample.scss</p> <p>For future reference, the settings are as follows: </p> <p><strong>./src/style/vars.scss</strong></p> <pre class="brush:php;toolbar:false;">$sample-var: red;</pre> <p><strong>vite.config.js</strong></p> <pre class="brush:php;toolbar:false;">import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], css: { preprocessorOptions: { scss: { additionalData: `@use "./src/style/vars.scss" as *;`, }, }, }, });</pre> <p><strong>./src/style/sample.scss</strong></p> <pre class="brush:php;toolbar:false;">@use 'sass:color'; .sample-style { color: $sample-var; }</pre> <p><strong>Component</strong>:</p> <pre class="brush:php;toolbar:false;"><script setup> </script> <template> <div class="sample-style">Hello sample style</div> </template> <style lang="scss" scoped> @import '../style/sample.scss'; </style></pre> <p>Using this code, I get <code>Undefined variable.</code> in <code>$sample-var</code> in <code>sample.scss</code> mistake. </p> <p>However, if I comment out <code>@use 'sass:color';</code>, it works as expected (I can access <code>$sample- var</code>). </p> <p>What's happening here? How do I properly import <code>sass:color</code> in my component style while using <code>additionalData</code> in <code>vite.config.js</code> A set of variables accessible globally? I'm interested in learning about best practices. </p>
P粉478445671
P粉478445671

reply all(1)
P粉268654873

Before the <style> tag of the component, the Scss code defined in additionalData will be added. So what the Sass compiler ends up processing is:

@use "./src/style/vars.scss" as *;
@import '../style/sample.scss';

According to the documentation , when sample.scss does not contain any @use statements:

This means that the above code is evaluated like:

@use "./src/style/vars.scss" as *;
.sample-style {
  color: $sample-var;
}

However, according to the documentation for importing module system files (emphasis mine):

$sample-var is a member of a module, so sample.scss cannot access $sample-var.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template