How do you use a scss mixin in an Angular component?
CONTEXT
I created a file for my scss mixins in /src/styles/_mixins.css and imported this mixins file into the global style file styles.scss like this
// styles.scss
@use "variables";
@use "mixins";
Then in the year-events.component.scss file of my angular component I tried to use my mixins like this
// year-events.component.scss
@use "mixins";
.events-grid {
display: grid;
grid-template-columns: repeat(1, 1fr);
gap: 2rem;
@include mixins.screen-size('large') {
grid-template-columns: repeat(4, 1fr)
}
}
it doesn't work and I get this error
Can't find stylesheet to import.
╷
1 │ @use "mixins";
│ ^^^^^^^^^^^^^
╵
src/app/calendar/components/year-events/year-events.component.scss 1:1 root stylesheet
And so, after several searches, it says to manually import the mixins file into my component's .ts file, which I did.
@Component({
selector: 'app-year-events',
standalone: true,
imports: [
EventCardComponent,
],
templateUrl: './year-events.component.html',
styleUrls: ['./year-events.component.scss', '/src/styles/_mixins.scss'], // added this
})
export class YearEventsComponent implements OnInit {}
but always the same error. What's the reason for this? Shouldn't importing something into the global style file styles.scss benefit all components?
voici mon fichier _mixins.scss
//_mixins.scss
@mixin screen-size($breakpoint) {
@if $breakpoint == 'small' {
@media (max-width: 600px) {
@content
}
} @else if $breakpoint == 'medium' {
@media (min-width: 768px) {
@content
}
} @else if $breakpoint == 'large' {
@media (min-width: 1024px) {
@content
}
}
}
Just to clarify, when I use the mixin in the styles.scss file, it works as follows
You need to specify the relative path to the _mixins.scss
file.
@use "../../../../styles/mixins";
Alternatively you can use the includePaths
property of the stylePreprocessorOptions
in angular.json
:
"stylePreprocessorOptions": {
"includePaths": ["src/styles"]
}
This allows you to use your existing component code:
@use "mixins";