sass-loader additionalData/prependData/data bloats bundle size

Viewed 3222

I'm using Vue2 and laravel-mix and I want to have my variables accessible globally. I eventually found this:

mix.webpackConfig({
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [
                    {
                        loader:  'sass-loader',
                        options: {
                            //this might be "data" or "prependData" depening on your version
                            additionalData: `@import "./resources/js/styles/variables.scss";`
                        }
                    }
                ]
            }
        ]
    }
})

This does make my variables globally accessible, but essentially copies the variables.scss into every single vue component, which massively bloats my bundle size.

How can I prevent this?

Edit: This only is an issue, when the imported file is relatively big. In my project, the imported file itsself imported a theme scss (to get access to the themes variables), which ultimately copied this whole thing everywhere I needed the variables.
I fixed this by defining my custom variables in a seperate file and using those variables in the "overwriting-variables" file, something like this:
custom-variables.scss

$red: #ff0000;

overwriting-variables.scss

import 'theme.scss'; //this bloated my project
import 'custom-variables';

$--theme-red: $red

And when I needed this theme color in my vue components I just imported the custom-variables.scss instead of overwriting-variables.scss.
This does fix my bloating issue, but doesn't fully solve the problem, I still have multiple instances of the custom-variables.scss in my project, it just doesn't matter because its really small. So I'd be still happy to hear about other solutions!

1 Answers

You need to separate your functions, variables & mixins from actual CSS rules.

These files will be imported and available to every component you write, which is great for things like variables, functions, or mixins, but you should avoid any actual CSS rules. Adding CSS rules to your shared Sass files will import those rules into every component and bloat your project. For global CSS rules, create a separate file and import it into your main App.vue file instead.

Source: https://austingil.com/global-sass-vue-project/

Related