Variable Name Error "is undefined" even though "variables.less" imported

I started using LESS today. But it's kinda weird. This code does not work. I get an error:

! Variable Name Error: @linkColor in a is undefined.

My bootstrap:

@import "variables.less";
@import "normalize.less";

variables.less:

@linkColor:             #08c;
@linkColorHover:        darken(@linkColor, 15%);

normalize.less:

a {
    color: @linkColor;
}
a:visited {
    color: @linkColor;
}
a:hover {
    color: @linkColorHover;
}

When I make an

@import "variables.less"

in the normalize.less file, everything works fine.

Thanks for your help :)


Solution 1:

This other question ultimately led me to the right answer.

It looks like the LESS compiler is silently failing if files are encoded with a BOM. (That's a Byte Order Mark for those not familiar with the term.) This is the default setting in some editors, such as Visual Studio.

The compiler barfs up an error on the BOM if it's in your root file, but seems to fail silently for @import-ed files.

Try saving your files as UTF-8 without a BOM, and see if that solves your problem.

Solution 2:

This error can also occur via bad imports in the files you're importing.

I also encountered this issue, when using multiple layers of import, and the 'lessc' compiler from Node.js:

  • The original file imported a file (which we will call 'child')
  • The child file imported a file (which we will call 'grandchild')
  • The grandchild was imported

I attempted to compile the original file, and received the same 'undefined variable' behavior. I could see the variable was defined in the child and the syntax lookedcorrect.

No prior errors were displayed.

The problem turned out that the child was not importing the grandchild properly. Ie,

@import grandchild.less

rather than:

@import "grandchild.less";

Fixing the child importing the grandchild made the original see the variables defined in the child.

This seems like a bug in less - ie, the bad import should show up in the 'lessc' output, so one day it will probably be fixed. Until then, I hope this helps.

Solution 3:

There may be another possible root cause.

Here is my original Gruntfile.js:

less: {
      compile: {
        files: {
          'css/less.css': 'less/**/*.less'
        }
      }
    },

The wildcard makes LESS compiler compile all .less files under that folder and merge all results into one CSS. And I got errors running grunt less:compile:

NameError: .transition is undefined in less/core/html.less on line 38, column 3

Once I changed 'less/**/*.less' into 'less/css.less', the compilation succeeds.

Solution 4:

I encountered the same problem using Winless compiler.

Some of the .less files i was importing into master.less were empty. when i removed these from the list of imported files my variables were recognized!