CSS-Redundancy when using LESS and its @import

2019-03-17 23:47发布

问题:

I really like the idea and the concept of LESS. Yet I stumbled upon a bug, which i reported quite a while ago to the author but did not yet get any feedback. Maybe it's just me who is doing something wrong.

My application.less-File that looks similar to this:

@import "reset";
@import "config";
@import "header";
@import "forms";
[…]

I like that it is possible to use the @import rule to split up my files to gain a better overview of my css-declarations. Yet every imported file needs to re-import the config.less-File again to be able to make use of the mixins and variables i defined in there.

I bet you already know about what kind of redundancy I am driving at: Everytime the config.less is imported, its "output" becomes part of the application.css.

My config-file contains about 200 lines of code. Since I split up my CSS-into about 5 files (based on my controller names) that need to re-import the config, I end up having about 1000 lines of generated CSS-Code that are 100% redundant.

Only solution that I can come up with is not to split up my files, what I really like to avoid.

回答1:

Although not ideal, the practical reason for this is that the files you import theoretically don't need to contain any CSS. Typically, you would have variables and dynamic mixins, which don't contribute to your CSS output:

lib.less:

#colors {
    @blue: #0011ff;
    @red: #ee2222;
}
.button (@width: 10px) {...}

main.less:

@import "lib";

a { color: #colors[@blue]; }

output, main.css:

a { color: #0011ff; }

#colors {} and .button will not be output in this case.



回答2:

LESS now supports @import-once "stylename.less";



回答3:

Maybe you can split them up in your development environment and then merge them together, not needing all the extra code, when you deploy to your live web server?



回答4:

You can use dynamic mixins in your LESS config file if they are declared and mixed-in using $ instead of ..

In config.less:

$mixin
{
  a { color: @light; }
  h2 { //etc.
}

In header.less:

@import "config";
.header
{
  $mixin;
}

Source. I've also tried this and it works.



标签: css less