Search code examples
sasspartial

Avoid replication when importing a base partial scss


I have the following structure of SCSS files: suppliers.scss: includes _base.scss, _sortable-table.scss and _product.scss _sortable-table.scss and _product.scss: includes _base.scss

_base.scss contains many variables that defines the layout, like the modulation and intercolumn size. Also, it contains base layout classes that are extended by others.

The problem is, as the partials and every style requires this base import, its contents then gets duplicated several times in the result css file. This causes a big overhead on the css.

So the problem is how to prevent this duplication. Any guess?

See the actual sources at https://github.com/coletivoEITA/noosfero-ecosol/tree/distribution-plugin/plugins/suppliers/public/stylesheets


Solution

  • You should take a closer look at the import-directives, extends and mixins and then refactor your code. You might want to start with a "superfile" (app.scss). This file basically does nothing more than importing all your created files in the order you need them.

    This could be the the typical content of an app.scss:

    @import "settings";
    
    @import "mixins";
    @import "extends";
    @import "browser-reset";
    
    @import "styles";
    @import "more-styles"
    @import "even-more-styles"
    @import "..."
    
    1. The first thing I do is to import all my settings/variables.
    2. After that i am importing my mixins which might already depend on some variables.
    3. Now i am importing my extends, which can now use variables & mixins.
    4. a browser-reset file
    5. My App-Styles which can make use of all the settings, mixins and extends i made so far.

    Make sure, that all other files apart of the app.scss are prepended with an underscore (e.g. _settings.scss) otherwise they will be created as separate css-files and of course throw errors when you used variables, mixins or extends in them.

    If you organize your code like this and start to use mixins and extends whenever it makes sense then you do not have to worry about bloated code anymore.