Why in Sass stylesheets, we should use @use to import code instead of using @import directly?
P粉493534105
P粉493534105 2023-09-15 21:45:03
0
1
760

I'm implementing a project and from what I understand, @use will only import the code into the stylesheet we use @use and not any other stylesheet.

sass documentation:

@use Loaded members (variables, functions, and mixins) are only visible in the stylesheet that loaded them. If other stylesheets want to access them, they need to write their own @use rules.

So I have a file called _b.scss which is the main file for my sass compiled to css and then I have a file called a.scss , in which I imported _b.scss via @use, then, I have a file called project.scss in which I imported a.scss, so according to this hierarchy, _b.scss should not be accessible in project.scss, but when I put project.scss When compiling to css, in my css file, I compile the scss code from _b.scss (however, if I write in project.scss like @debug map-get($colors."red")It will throw an error), so why does this happen?

PS: I use gulp to compile, clean and monitor my scss and css.

//文件层次结构

index.html
gulpfile.js
a.scss
_b.scss
project
  project.scss
css
  project.css
//index.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/project.css">
<title>Document</title>
</head>

<body>
<div class="bg-red">hey</div>
<div class="bg-purple">hey</div>
</body>

</html>
//_b.scss

 $colors:(
 "red":red,
 "blue":blue,
 "green":green,
 "yellow":yellow,
 "brown":brown,
 "purple":purple
 );

 @each $key,$val in $colors{
 .bg-#{$key}{
 background: $val;
 }  
 }
//a.scss

@use "b";
//project.scss

@use "../a";
//project.css

.bg-red {
background: red;
}

.bg-purple {
background: purple;
}
//gulpfile.js

const { src, dest, watch, series } = require('gulp')
const sass = require('gulp-sass')(require('sass'))
const purgecss = require('gulp-purgecss')

function buildStyles() {
return src('project/*.scss')
    .pipe(sass({}))
    .pipe(purgecss({ content: ['*.html'] }))
    .pipe(dest('css'))
}

function watchTask() {
watch(['project/*.scss', '*.html'], buildStyles)
}

exports.default = series(buildStyles, watchTask)

P粉493534105
P粉493534105

reply all(1)
P粉316423089

Based on your own quote (emphasis mine):

Please note that this does not include style rules. According to Documentation, style rules are still "loaded" into the generated stylesheet:

Therefore, @use is used to isolate visible members (variables, functions, and mixins) while outputting style rules.

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