It is currently not possible to use SASS to include files dynamically. @import
cannot be used within control directives (e.g. @if
) or mixins, using a variable in an import directive is erroneous syntax, and there is no directive for ending file execution early (which effectively would allow conditional imports). However, you can solve your issue by changing how you structure your style rules.
NOTE
There is a SASS plugin that will modify @import
to only
include files once. However,
- Your code will have added dependence on the environment
- We would all do better to understand how style rules are intended to be structured, which would avoid any duplicate rules.
@import
may soon be deprecated. The SASS team is planning "large-scale redesign of importing", so re-import protection
might be part of future versions of SASS, as it is popular
requested feature.
Solution
If you have styles that are conditionally included from multiple files, they are not 'global' styles. These styles should be encapsulated in mixins, in 'module' or 'library' files. The main idea is that importing one such file will not output any css. This way, you can import these files redundantly so you can use the mixins wherever you need them.
If you need to do this with variables, then:
- Make sure you define variables before including mixins, otherwise they are only available in the mixin scope. A good way to do this is to define all default variables in a vars.sass file, and import it along with imported modules/libraries so the variables are available globally.
- Define variables using
!default
in the mixin, so it can be overridden even before the mixin is called (like in a vars.sass file).
If you have top-level styles that you want to ensure are defined without having rigid inclusion rules, you can use this mixin:
$was-defined: () !default;
@mixin define-once($name) {
@if not index($was-defined, $name) {
$was-defined: append($was-defined, $name);
@content;
}
}
// Example:
@include define-once('body-typography') {
body {
font-size: 100%;
line-height: 2em;
color: #444;
font-family: monospace;
}
}
For more good practices on structuring your code like this, check out this article.