SASS: Using @extend with @use

Viewed 2305

I have the two following files:

main.scss
|- base
|  |- _typography.scss

The _typography.scss file contains:

$font-family: Roboto;

%typo-button{
    font-family: $font-family;
    font-size: 14px;
    font-weight: 500;
    text-transform: uppercase;
}

Now I am triying to @extend a class in main.scss with the placeholder %typo-button.

@use 'base/typography';

.button{
    display: inline-block;
    height: 48px;
    padding: 12px 0px;
    @extend typography.%typo-button;
}

The following error is thrown:

Error: Expected identifier.
│     @extend typography.%typo-button;

So what is the correct syntax to use @extend with @use? Using @use with a @mixin is no problem, e.g.@include typography.my-mixin(). But I would like to use @extend instead of mixins in some cases.

2 Answers

Namespace prefixes are not necessary on @extends - only on functions, mixins, and variables. Remove typography. and it should work:

@use 'base/typography';

.button{
    display: inline-block;
    height: 48px;
    padding: 12px 0px;
    @extend %typo-button;
}

(The upstream limitation mentioned above means that the "typography" module can't extend anything inside the "main" module that uses it – but selectors in "main" can extend selectors in "typography".)

I believe there are two ways for you to solve this problem:

the first is to use @mixin instead of %typo-button and @include typography.typo-button instead of @extend typography.typo-button

OR

you need to @use '../main' inside of _typography.scss to have access to %typo-button (I think that is what is meant by the docs when they say

extension will only affect style rules written in upstream modules—that is, modules that are loaded by that stylesheet using the @use rule or the @forward rule, modules loaded by those modules, and so on

here https://sass-lang.com/documentation/at-rules/extend#extension-scope)

UPDATE: the second option is not correct per Miriam. See her answer to correctly use @extend.

Related