Question
How can I efficiently import variables.scss
globally without the need to duplicate them in every file and reference them in my build instead of importing?
Setup
I am using Vue2 with laravel-mix, where I have imported index.scss
in my main.js
variables.scss
$--test: #ff0000;
index.scss
@import 'variables';
.dashboard-title {
color: $--test;
}
The title is successfully colored red. However, attempting the same inside a component does not work:
<style scoped lang="scss">
.dashboard-title {
color: $--test;
}
</style>
Even though index.scss
is global, the same behavior is not seen with variables.scss
when imported in a global index.scss
.
To resolve this issue, importing the variables file in each component resolves the error but results in duplicating the entire content of variables.scss
every time it is imported into a Vue component.
Analyzing my bundle using a webpack bundle analyzer revealed an increase in bundle size due to multiple imports of the variables file: webpack bundle analysis image (sections marked in blue show increased size as variables file is imported)
There is a potential 20% reduction in bundle size if the content duplication issue is addressed...
What I've tried:
https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/ (unable to adapt for laravel-mix configuration)
Attempted to use purgeCss
resulting in style issues but reducing bundle size by 50%
Added to the webpack.mix.js
:
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 approach makes the variables global but still duplicates them for every vue component, regardless of usage.
Edit: Issue arises when the imported file is large. In my case, the imported file included a theme scss file which caused duplication everywhere the variables were needed.
Resolved by defining custom variables in a separate file and utilizing them in an "overwriting-variables" file like:
$red: #ff0000;
overwriting-variables.scss
import 'theme.scss';
import 'custom-variables';
$--theme-red: $red
Simply import custom-variables.scss
instead of overwriting-variables.scss
where necessary in vue components.
This mitigates bloating, yet the issue persists with multiple instances of custom-variables.scss
in the project, albeit being small so far. Seeking alternative solutions!