'How to properly override variables of an Angular Library

I am basically making a small design library using bootstrap 5 and Angular. I am using boostrap core, add some extension or custom style to it (to fit my design).

Basically, I use bootstrap as follow :

LIBRARY :

I have 2 scss in my library :

design-library.core.scss

// Required to be imported for bootstrap
@import '~bootstrap/scss/functions';

// Library default variable that override bootstraps one
@import './variables'; 

design-library.extension.scss

// I need to import the variables or they are undefined 

@import './variables'
// some override of bootstrap style like 
.alert {
  background: $white;
}

PROJECT :

Now, In my project, I use the design-library as follow :

project.scss

// Import the default variable of the libraryu
@import '~/design-library.core';

// override the default with additional variables
@import './project-variables'

// import bootstrap
@import '~bootstrap';

// import the extension of bootstrap from the library
@import '~/design-library.extension'

This works great, the problem I have tho, is with variables overrides.

Let's say I put $red: #f00 as default in the library.

Then, In the project variables I set $red: #e30000

In my library extension when import variables, I import the one of the library (since I can't import the one of the project of course...). But since I import the one from the Library (and not the override one), all my CSS will be generated with $red: #f00. I want instead all my extension css to use overridden variable so it should be $red: #e30000

How can I import variable after they have been overridden by the project that implements them ?

EDIT : Is this clear enough ? :x



Solution 1:[1]

It sounds like you want to override some variables within design-library.extension.scss. The only way to do that is by importing another file.

@import './variables'
@import './overrides'
// some override of bootstrap style like 
.alert {
  background: $white;
}

However, it sounds like you want this file to somehow know that you've overridden these variables in the project.scss file. Sorry, but that just doesn't make sense.

When you override the variables in project.scss they have not been "overridden by the project", they've only been overridden in that one single file. For your extension to know of these overrides, it would need to import project.scss.

That being said, I do not recommend trying to import external files if you plan on releasing this library as a package, that would make it extremely fragile.

If this is just for personal use, you can import your project-variables file after ./variables in design-library.extension.scss.

I hope that clarifies things for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1