John Ohara
John Ohara

Reputation: 2901

Duplicate styles using Less CSS

I've recently moved to using Less with the bundle functionality of Web Essentials (VS2017).

Although I'm only currently developing, I noticed my style sheet was getting very big - 15,000 lines to date in un-minified form. On further investigation it turned out that lots of selectors were being duplicated in the output file.

At the moment, I'm not sure if the issue is caused by Web Essentials or I'm misunderstanding how Less works.

The way I've set it up is that every component has its own .less file.

In order for the whole thing to compile I have to reference other less files as required, here's an example:

@import "../varGlobal.less";
@import "mdc-core-button.less";
@import "../Boilerplate/Iconography.less";
@import "../Prefix/mixTransition.less";

.mdc-icon-button_theme--dark {
    &:extend(.mdc-button_state--dark all);

    &[data-inactive] {
        color: @textDark3;
    }

    &:not([data-inactive]) {
        color: @textDark2;

        &:focus {
            color: @textDark1;
        }
    }
}

The way it stands, less produces an individual CSS file for each component, then they're all bundled together by Web Essentials.

The problem being that the code for all the imported functions is included in the CSS input file, which is then bundled many times in the final output file.

I've tried adding the reference keyword to the import statements, which does work in cutting out the duplicates, but all of the 'extended code' is added back in to the input file instead of being referenced as part of the main output file.

@import (reference) "../Prefix/mixTransition.less";

Here's a snippet from my bundle file - not all less style sheets are included but it should give a flavour.

[
  {
    "outputFileName": "Assets/Styles/MainBundle.css",
    "inputFiles": [

      "Assets/Styles/Components/mdc-core-button.css",
      "Assets/Styles/Components/mdc-icon-button.css",
      "Assets/Styles/Components/mdc-top-app-bar.css"
    ]
  }
]

In some instances where I have utility code, the same selector is being repeated 20 or more times.

What am I doing wrong?

** UPDATE **

Given that the reference keyword and extend functionality both save lines in the style sheet, if they don't work together, then its a case of finding the one that saves most space.

I've added the reference keyword to all my input files and the number of lines has reduced from 15,000 to 5,000. It seems that the extend functionality still works to some degree but only if the selectors are in the same file - which they aren't in 99% of cases.

Upvotes: 2

Views: 461

Answers (0)

Related Questions