Sass undefined variable on precompilation

geraddavis picture geraddavis · Mar 14, 2014 · Viewed 12.3k times · Source

I'm upgrading our Rails (3.2.17) app over to sass and I'm running into "undefined variable" errors during asset precompilation. I use @import to include my snippets in the master.scss file. This setup works great locally, but errors on precompliation. The only way to get around the errors is to @import snippets into snippets which reference the mixins and variables defined in the first snippet.

For example: I @import 'fonts' and 'buttons' into master.scss and then I have to @import 'fonts' a second time into 'buttons' because it uses a variable defined in 'fonts'. This gets around the precompliation error, but it's not ideal because instead of only one instance of 'fonts' being loaded into the app, there is now two.

@importing all the snippets only the one time into master.scss works locally when I don't precompile. There has to be a solution to this. Any thoughts?

Answer

anbiniyar picture anbiniyar · Mar 14, 2014

You are seeing this error because you are using application.css with require directive.

From SASS rails documentation.

Sprockets provides some directives that are placed inside of comments called require, require_tree, and require_self. DO NOT USE THEM IN YOUR SASS/SCSS FILES. They are very primitive and do not work well with Sass files. Instead, use Sass's native @import directive which sass-rails has customized to integrate with the conventions of your Rails projects.

Simply, rename your application.css to application.css.scss (using .sass didn't work for me). Remove everything other than require self. Include your global @import statements there.

One additional note is that you will need to add all css files as @import manually to your application.css.scss. I normally create a folder app/assets/stylesheets/app and add @import app/**/* as a final entry to the application.css.scss

I hope this helps.