Error undefined mixin

Getting the dreaded SASS error of undefined mixin? This post will go over a few tips to fix this!

Introduction

Recently, I was working on a project using SASS (https://sass-lang.com/) as their CSS processor. One issue that I came across is the dreaded “undefined mixin”:

ERROR ./styles/app.scss

SassError: Undefined mixin.

Mixins are just a simple piece of styling code that allows you to reuse across the project. You declare the mixin with the @mixin at-rule and and use it with the @include rule.

Understanding the difference between @import and @use

Both of these rules do the same thing in the end. The main difference is that @import takes everything to to a global namespace. With @use, we need to scope it to a specified namespace.

The Sass team discourages the continued use of the @import rule. Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead.

Fix 1 — Check the mixin name is correct and using the correct syntax

A common reason why this error appears is that we are not following the correct syntax or mispelling the mixin.

Make sure that we are using the @use or @import keyword correctly and in the main scss file, properly use the @include keyword

To setup SASS correctly to use mixins, consider the following folder structure and go through the steps:

.
└── My-Project/
    ├── _mixins.scss
    └── styles.scss
  1. Open up the My-Project folder in VSCode. Make sure you have installed the Live SASS Compiler extension (this is just for demonstration you can use the equivalent SASS CLI).
  2. Open the _mixins.scss and add a mixin to set the theme of the page:
@mixin theme($theme: DarkGray) {
    background: $theme;
    box-shadow: 0 0 1px rgba($theme, .25);
    color: #fff;
}
  1. Open the styles.scss and add @use "mixins" :
@use "mixins" as m;

*, *::before, *::after{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.info {
    @include m.theme;
}

A few things to note so that we dont get the undefined mixin error:

  • Check that when we @use you have to have the as <namespace>. So in our example code, we have @use "mixins" as m;
  • Make sure to check the code ends with semicolon (;)
  • Check case sensitivity — SASS is case sensitive. For example a mixin of @mixin theme is different to @mixin Theme
  • When including the mixin with the @include keyword, make sure to include the namespace. In our example above this is @include m.theme;
  • Verify that the code for the mixin file (_mixins.scss) does not have any errors! Make sure that we are not overriding any reserved SASS keywords.

Tip: @use rule needs to be before any other rules

A stylesheet’s @use rules must come before any rules other than @forward, including style rules. However, you can declare variables before @use rules to use when configuring modules.

Whats with the underscore in the filename?

In SASS, when a file starts with a underscore this means a partial file. You might name it something like _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @use or @import rule.

Alternative to @use with @import

Now if you do not prefer to specify the namespace, you can do @use "mixins" as m;. Another way is using the @import rule.

@import "mixins";

*, *::before, *::after{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.info {
    @include theme;
}

Notice how we do not need to declare the namespace of “m”. Everything will be accessible globally!

Fix 2 — Verify the mixin path

Another common reason why the “undefined mixin” error comes up with using SASS is that we are not specifying the paths correctly.

When SASS compiles .scss files to css, it takes URL format not file path format. So you will have to use forward slashes (/) instead of backward slashes that you find on operation systems such as Windows ()

This is just to ensure that it works consistently across multiple operating systems.

As an example, consider the following folder path:

.
└── My-Project/
    ├── new_styles/
    │   └── _custom_mixins.scss
    ├── _mixins.scss
    └── _styles.scss
@use "new_styles/custom_mixins" as customMixins;

*, *::before, *::after{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.info {
    @include customMixins.theme;
}

Notice that our new @use rule is @use "new_styles/custom_mixins" as customMixins; — we do not need to define the relative path thats required on some operating systems (eg ./)

Tip:Loading partials

Partial files let SASS know to not compile it into CSS. You can leave off the _ when importing a partial.

Undefined mixin with Bootstrap

This issue of undefined mixin comes up frequently when using Bootstrap. The problem here is that Bootstrap uses @import to import its external SCSS files.

Since SASS is moving away from @imports and recommending to use @use, if we try to extend Bootstrap with @use we will get a lot of thes “undefined mixin” errors:

Consider the following SCSS that comes with Bootstrap — importing functions and variables:

@import "~bootstrap/scss/functions";
@import "~bootstrap/scss/variables";
@import "~/bootstrap/scss/mixins";

Now if we try to refactor with @use at-rule, we get the following:

@use "~bootstrap/scss/functions" as bootstrap_func;
@use "~bootstrap/scss/variables" as bootstrap_var;

If you complile this, you will get an error of something similar:

SassError: @use rules must be written before any other rules.

The problem is due to the fact that the @use at-rule only makes names available in the current stylesheet, as opposed to globally.

This means that the file ~bootstrap/scss/variables does not know about the functions declared in ~bootstrap/scss/functions.

With the @import rule, all the functions, mixins and variables are available globally, so it will.

In this case, there is not much we could do, but keep using @imports. To fix this the Bootstrap team needs to rewrite their codebase to structure in a way that is @use friendly!

Chasing down this issue, the Boostrap team mentions that their reasoning for not using the @use rule is not wide support in most build systems.
(https://github.com/twbs/bootstrap/issues/30025#issuecomment-574825600)

Summary

In this post, I went over the SASS error of undefined mixin when compiling SASS files to CSS files. This error is usually caused by incorrect usage of the syntax (@use, @import, @include).

Make sure that we are using namespaces with @use at-rule, check for case-sensitivitiy, and not using any SASS reserved keywords

Another reason is that we are not referencing the correct path when using the mixin. SASS follows the URL format for loading modules not filepath format. This is to allow compatibility across operating systems.

SassError: SassError: Undefined mixin. sass variable or mixins not getting identified in Angular 12 scss application.

My _mixins.scss file content:

@mixin horizontal-box {
display: flex;
flex-direction: row;
}

@import url(«../app/_mixins.scss»);

.result-box {
@include horizontal-box;
}

this is a freshly created angular 12 application with commmand: ng new angular12app

it straight away gave the error on command: ng serve

./src/app/app.component.scss — Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: SassError: Undefined mixin.

4 │ @include horizontal-box;
│ ^^^^^^^^^^^^^^^^^^^^^^^

srcappapp.component.scss 4:3 root stylesheet

I lost 3 hours on this issue. Did not expect this from Angular.

Submitting an Issue

version of Angular CLI used: Angular 12.

Angular.json:
{
«$schema»: «./node_modules/@angular/cli/lib/config/schema.json»,
«version»: 1,
«newProjectRoot»: «projects»,
«projects»: {
«angular12»: {
«projectType»: «application»,
«schematics»: {
«@schematics/angular:component»: {
«style»: «scss»
},
«@schematics/angular:application»: {
«strict»: true
}
},
«root»: «»,
«sourceRoot»: «src»,
«prefix»: «app»,
«architect»: {
«build»: {
«builder»: «@angular-devkit/build-angular:browser»,
«options»: {
«outputPath»: «dist/angular12»,
«index»: «src/index.html»,
«main»: «src/main.ts»,
«polyfills»: «src/polyfills.ts»,
«tsConfig»: «tsconfig.app.json»,
«inlineStyleLanguage»: «scss»,
«assets»: [
«src/favicon.ico»,
«src/assets»
],
«styles»: [
«src/styles.scss»
],
«scripts»: []
},
«configurations»: {
«production»: {
«budgets»: [
{
«type»: «initial»,
«maximumWarning»: «500kb»,
«maximumError»: «1mb»
},
{
«type»: «anyComponentStyle»,
«maximumWarning»: «2kb»,
«maximumError»: «4kb»
}
],
«fileReplacements»: [
{
«replace»: «src/environments/environment.ts»,
«with»: «src/environments/environment.prod.ts»
}
],
«outputHashing»: «all»
},
«development»: {
«buildOptimizer»: false,
«optimization»: false,
«vendorChunk»: true,
«extractLicenses»: false,
«sourceMap»: true,
«namedChunks»: true
}
},
«defaultConfiguration»: «production»
},
«serve»: {
«builder»: «@angular-devkit/build-angular:dev-server»,
«configurations»: {
«production»: {
«browserTarget»: «angular12:build:production»
},
«development»: {
«browserTarget»: «angular12:build:development»
}
},
«defaultConfiguration»: «development»
},
«extract-i18n»: {
«builder»: «@angular-devkit/build-angular:extract-i18n»,
«options»: {
«browserTarget»: «angular12:build»
}
},
«test»: {
«builder»: «@angular-devkit/build-angular:karma»,
«options»: {
«main»: «src/test.ts»,
«polyfills»: «src/polyfills.ts»,
«tsConfig»: «tsconfig.spec.json»,
«karmaConfig»: «karma.conf.js»,
«inlineStyleLanguage»: «scss»,
«assets»: [
«src/favicon.ico»,
«src/assets»
],
«styles»: [
«src/styles.scss»
],
«scripts»: []
}
}
}
}
},
«defaultProject»: «angular12»
}

version of Angular DevKit used: «@angular-devkit/build-angular»: «~12.0.1»,

3rd-party libraries and their versions: none

Most importantly — a use-case that fails:

Step 1:
create a file: _mixin.scss in the root folder: ->
content of the _mixin.scss
@mixin horizontal-box {
display: flex;
flex-direction: row;
}

Step 2:
import the mixin to app.component.scss:

@import url(«_mixin.scss»);

.result-box {
@include horizontal-box;
}

Step 3: Run ng serve from console:
Error:
./src/app/app.component.scss — Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: SassError: Undefined mixin.

4 │ @include horizontal-box;
│ ^^^^^^^^^^^^^^^^^^^^^^^

srcappapp.component.scss 4:5 root stylesheet
at Object.callback (D:PROJECTSAngular12angular12node_modulessass-loaderdistindex.js:54:16)
at Worker. (D:PROJECTSAngular12angular12node_modules@angular-devkitbuild-angularsrcsasssass-service.js:123:25)
at Worker.emit (node:events:365:28)
at MessagePort. (node:internal/worker:241:53)
at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:461:20)
at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28)

Hopefully You understood what to do. If not ping back, I will respond.

I have attached the source:

app.zip

In case, You have this feeling that , You do not have the source. Kindly request You not to close this thread on Your own

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

I’m working my way through ‘Add Conditional Logic to Your Stylesheets’ and I’m working in Dreamweaver and compiling through the CMD line. Everything has been hunky dory until I encountered a very bamboozling problem.

I’ve set up the media queries mixin (mq) and have nested it in .img-container. I’m using it to set the image display to hidden on xs screen sizes. However, it refuses to compile as it does not recognise the mixin. I’ve had a play around and found that the mq mixin is recognised on the other scss files where I’ve used it, but not on this one (_images.scss).

Am I missing something? Is this something that I will kick myself for when it’s pointed out? Only YOU have the answer! ;)

Here’s the code I’m using btw. Pretty much the same as Guil’s in the exercise.

.img-featured {
  @include roundy(165px, 4px solid $white);
  margin-top: 75px;
  position: relative;
  z-index: 100;
    @include mq('xs') {
        display: none;
    }
}
// Media queries
@mixin mq($break) {
    @if $break == 'xs' {
        @media (max-width:$break-xs) {
            @content;
        }
    }
    @else if $break == 'sm' {
        @media (min-width:$break-s) {
            @content;
        }
    }
    @else if $break == 'med' {
        @media (min-width:$break-m) {
            @content;
        }
    }
    @else if $break == 'lg' {
        @media (min-width:$break-l) {
            @content;
        }
    }
}

2 Answers

Jonathan Grieve

MOD

Is there a chance you haven’t imported theimages.scss file, which is why it’s not recognising the mixin?

Also it’s a little hard for me to guess with just the code above but I also noticed when I put the code into sassMeister it was pulling up line 5 in the Media Query code

        @media (max-width:$break-xs) {

Undefined variable.

Which is probably because it exists elsewhere in your project but I found that by changing all the variables in the media queries to $break it compiled.

But I’m afraid these are only guesses as far as my eyes can see :)

Gemz Nunn May 3, 2019 10:53am

I’m using Dart Sass, installed via Chocolatey (which is awesome!)

In short: You get the sass error «undefined mixin» and you’re sure that that mixin is in scope? Check all your sass partial files for a leading underscore. If not sass will try to compile this partial with it`s own scope which probably lacks all of the global mixins & other data. Pretty obvious but easy to miss in a bigger folder structure.

Using the middleman gem, I ran into a problem during the build process. I got an error «undefined mixin» even though the development server was running without any problem.

My main styles.css.scss file has an @import «base/base» which imports itself a couple of settings, global mixins and more.

So these settings and mixins should be in scope for every following import in styles.css.scss. I really wondered when I hit this problem. My first solution was really dirty, impulsive and so WRONG. I located the scss files which caused the problem, I tossed in a quick @import «base/some/mixin». Now the mixin was found. I did this for a dozen files. And guess what? I wondered why my exported css files was so mind-boggling bloated. I got around 25000 lines of css. Well a lot of them was sass debug output. But even without counting them my css fiel was pretty big.

The second anbormality I spotted was this in my compiled styles.css:

@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);
@import url(http://fonts.googleapis.com/css?family=Merriweather:300);

/* normalize.css v2.0.1 | MIT License | git.io/normalize */

So something was really wrong. This import is located in «base/fonts» and shut be imported only once during my initial @import «base/base»

Solution???
I found out that I had some scss files without a leading underscore. Of course! That’s the problem. During build sass tried to compile those files as a separate stylesheet with a separate scope- missing all the global import of my main styles.css.scss file.

I added the missing underscore to those scss partials, cleaned all my mistakenly placed imports and voilá less than 2500 lines including the compact sass debug output. Phew..

Я создал файл миксина с кодом.
@mixin size($a,$b: $a) {
width: $a;
height: $b;
}`

в главном файле стилей прописал путь
@import «utils/libs»;
@import «utils/vars»;
@import «utils/mixins»;
@import «utils/fonts»;

html {
font-size: $base-font-size;
height: 100%;
}

body {
background-color: $main-bg-color;
color: $base-text-color;
font-family: $main-font;
height: 100%;
}

h1, h2, h3, h4, h5, h6 { margin: 0; }

ul, li {
list-style-type: none;
margin: 0;
padding: 0;
}

a {
color: $base-text-color;
text-decoration: none; }

p { margin: 0; }

audio,
canvas,
iframe,
img,
svg,
video,
textarea { vertical-align: middle; }

textarea { resize: none; }

section { position: relative; }

input,
select,
button { outline: none; }

*,
*::before,
*::after { box-sizing: border-box; }

.wrapper {
display: flex;
flex-direction: column;
height: 100%;
}

.content { flex: 1 0 auto; }

.container {
margin: 0 auto;
max-width: $content-size;
padding: 0 80px;
width: 100%;
}

//Модули
@import «modules/modules»;`

в файле location я обращаюсь к миксину
.location {
$locationWidth: 185px;
flex: 0 0 $locationWidth;
width: $locationWidth;
&__header {
align-items: center;
cursor: pointer;
display: flex;
& > * {
&:not(:last-child) { margin-right: 10px; }
}
}

&__icon {
@include size(16px);
fill: $base-text-color;
}

&__current {
align-items: center;
display: flex;
&:after {
content: ‘ ‘;
border-style: solid;
border-width: 4px 4.5px 0 4.5px;
border-color: #000000 transparent transparent transparent;
margin-left: 10px;
height: 0;
width: 0;

}
}
}`

location импортится в small-blocks

который прописан в модулях

@import «buttons/buttons»;
@import «footer/footer»;
@import «header/header»;
@import «navigation/navigation»;
@import «small-blocks/small-blocks»;
@import «user/user»;

но при компиляции не видит миксин

C:OpenServerdomainsvenevskydevstaticstylesm odulessm
ch small-blocks.scss small-blocks.css
Error: Undefined mixin.
?
15 │ @include size(16px);
│ ^^^^^^^^^^^^^^^^^^^
?
location.scss 15:3 @import
small-blocks.scss 1:9 root stylesheet

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Понравилась статья? Поделить с друзьями:
  • Error undefined is not a function
  • Error unable to parse перевод
  • Error undefined feed rate grbl что делать
  • Error unable to open rom file
  • Error unable to open log file