Global scss variables for Angular components without importing them everytime - css

I do already have SCSS variables defined in src/styles/settings/_variables.scss and I am importing them into src/styles.scss, but still these variables aren't available for every single component.
Is there any way to make a global file which holds all SCSS variables for the rest of my components? Because writing #import in every single component .scss file it is very frustrating, especially if I have many nested components.
I know, there is a lot of similar questions, but it seems like they're all outdated and do not relate to the recent versions of Angular.
I use Angular 7.3 with CLI.

You just need to add a little more config, so where you are declaring your global variables, you need to wrap it up in :root{}. So in src/styles/settings/_variables.scss.
:root
{
--blue: #00b; // or any global you wish to share with components
}
Then when you use them in the SCSS you will need to access them like so.
.example-class {
background-color: var(--blue)
}
To add to this regarding comments, this method can use mixins, #media and keyframes and is not limited to just colours / font. That was an example.
From my understanding you need a global file src/assets/style/global and then to import each scss file into there where you are defining them like so.
#import 'filename';
If you dont want global variables to be used in within a component look when you have the globals working. Look into ViewEncapsulation, as this can be used to ignore them.

Is there any ways to make global file with scss variables available for all components?
Without importing global file everytime in each component, you want those sass variables been available, it's not possible.
The way it works in SASS, if using partials to better organize code, you can apply #import directive for referencing. So if there're some sass variables in shared/_variables.scss:
$lightslategray: #778899;
$darkgray: #A9A9A9;
and these variables need to be used in another stylesheet, stylesheet with them must be #import-ed into it firstly:
// Shared
#import "shared/variables";
.content {
background: $lightslategray;
}
In Angular it works in a similar way (related referencing external stylesheet). So if you need some sass variables, mixins or functions to be used by a particular component.scss, there is no other clean way, but to reference them in that component.scss using #import directive. To ease the task, you can create a file src/_variables.scss and use syntax like this in your component.scss:
#import “~variables.scss”;

step one : go to custom scss file (shared/css/_variable.scss) and write this part
:root{
--color-text: red;
--color-btn-success: green;
}
after go to style.scss (this is main file) and import this file :
#import './shared/css/Variables';
now you can use variables in all components with this Syntax:
.sample{
color : var(--color-text);
}

Easily possibe to access sass style(s) from a global file with two steps.
Add folder path of the style files to includePaths array in angular.json file.
Import style file by file-name in any component.
let say your files and folder structures is as follows: src > my-styles-folder > var.scss
angular.json
"architect": {
"build": {
...
"options": {
"stylePreprocessorOptions": {
"includePaths": [
"src/my-styles-folder" // add path only, do not include file name
]
},
"styles": [
...
]
}
...
}
}
some-component.scss
#import "var"; // var.scss
mat-toolbar {
height: $toolbar-height;
}

In angular 8 work for me.
In your _variable.scss file you have to add:
:root{--my-var:#fabada}
After that go in your angular.json and add this in "styles":
{"input":"yourPath/_variables.scss"}

Related

How can I make a sass file global instead of importing it in every file and bloating bundle size?

Question
How can I globally import variables.scss 1. without importing them in every file and 2. by referencing instead of duplicating them in my build?
Setup
I use Vue2 and laravel-mix and I have index.scss imported in my main.js
variables.scss
$--test: #ff0000;
index.scss
#import 'variables';
.dashboard-title {
color: $--test;
}
This colors the title red. But when I try to do the same thing inside of the component, it doesnt work:
<style scoped lang="scss">
.dashboard-title {
color: $--test;
}
</style>
This doesn't work, but I proved that index.scss is global in my first example. How is
variables.scss not global, when I import it in my global index.scss?
I can fix the error by importing the variables file in the component, but by doing this, I essentially duplicate the whole variables.scss file every time I import it in a vue component.
I found this out by analyzing my bundle with a webpack bundle analyzer, this is the output:
webpack bundle analysis image (all blue crossed parts are increased in size because the variables file is imported, this isn't a big problem now, but this will exponentially increase my bundle size with time)
It would reduce my bundle size by atleast 20% right now...
How can I reference the variables.scss file instead of duplicating its content?
What I've tried:
https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/ (I wasn't able to "migrate" this to a laravel-mix config)
I've also tried using purgeCss to remove duplicate css, this just completely messed up my styles but reduced the bundle size by 50% lol
Adding this 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 does make the variables global, but imports(duplicates) them for every vue component, even if they aren't being used.
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 (yet) because its really small. So I'd be still happy to hear about other solutions!
If you import every .scss in your index.scss, then every variable should work. Try this in your vue.config
css: {
loaderOptions: {
// by default the `sass` option will apply to both syntaxes
// because `scss` syntax is also processed by sass-loader underlyingly
// but when configuring the `data` option
// `scss` syntax requires an semicolon at the end of a statement, while `sass` syntax requires none
// in that case, we can target the `scss` syntax separately using the `scss` option
scss: {
prependData: `#import "#/style/index.scss"`
}
}
},
So I got it working with laravel-mix like 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";`
}
}
]
}
]
}
})
Not sure yet if this prevents the duplication though
Edit: It does not prevent duplication, it does increase the bundle size in every vue component. So I now have a 150% bigger bundle, because the variables file is imported in every single vue component. Even if the variable isn't even used.

Can't access global SASS variables from my component

In my Nuxt app I load all my SASS thus:
css: [
'~assets/scss/main.scss'
],
It works perfectly, except when I'm trying to use some SASS variable from within a component.
<style lang="scss">
.container {
background-color: $white;
}
</style>
In this case I get this error message:
SassError: Undefinied variable: $white
Yet, all of the SCSS contained in the SASS file where the variable is defined works throughout the app.
It is as if the app as a whole knew these files, but each individual component doesn't.
What's going on?
Most of the other answers don't take into account that Nuxt.js hides all the Webpack setup and forces you to do everything through nuxt.config.js.
My guess is that Webpack isn't compiling all the SCSS declarations together and therefore can't find the variable.
It's been a few months since I had this issue so things may have changed but here goes...
Make sure you have the correct Node packages installed (Nuxt DID NOT do this by default for me) npm i -D node-sass sass-loader
Add your CSS & SCSS files to the css: [] section of nuxt.config.js Order matters here so make sure things like variables are added before things that use them if you have separate files.
If you're using layouts (I think that's the default Nuxt setup) make sure that layouts/default.vue has a <style lang="sass"></style> block in it. If I remember correctly this can be empty but had to exist. I only have one layout but it may need to exist in all of them.
If all that seems like too much of a pain, there's a Nuxt Plugin that takes most of the work/management out of that process. Nuxt Style Resources Module
The confusing part is that:
styles from scss files CAN be loaded like this
//nuxt.config.js
css: [
'~assets/scss/main.scss'
],
//global scss file
$varcolor: black
h1{background: $varcolor}
BUT
the variables inside CAN NOT be used inside a component
//inside component
.component {background: $varcolor} // DOES NOT WORK
I also suggest the use of the nuxt style resource module:
https://github.com/nuxt-community/style-resources-module
new founded solution, checked and it's work. Founded here
add #nuxtjs/style-resources
export default {
css: [
'vendor.min.css'
],
modules: [
'#nuxtjs/style-resources'
],
//You will have to add this new object if it doesn't exist already
styleResources: {
scss: ['./assets/scss/main.scss'] // here I use only main scss with globally styles (variables, base etc)
},
}
it's strange, but if u change tilda (~) to dot(.), it's help for someone
from css: [ '~assets/scss/main.scss' ] to css: [ './assets/scss/main.scss' ]
this solution finded here
Us should either load the scss in your component
<style lang="sass">
#import 'path/to/your/_variable.scss'; // Using this should get you the variables
.my-color {
color: $primary-color;
}
Or adding the following to you to your vue.config.js
module.exports = {
css: {
loaderOptions: {
sass: {
data: `#import "#/pathto/variables.scss";`
}
}
}
};
Ref:
SassError: Undefinied variable: $white
Each <style lang="scss"> is compiled individually. You need to #import the file which defines $white into your component before the parser knows what $white means.
This is why most frameworks keep their variables in a _variables.scss file which is imported in all the other SCSS files/contexts.
The _variables.scss is not even loaded in the page, because in most cases it doesn't actually contain any rules. It only contains variable definitions which are imported into other .scss files, which output .css.
Ref:
Yet, all of the SCSS contained in the SASS file where the variable is defined works throughout the app.
If you import an SCSS file in your vue.config.js the output will be an ordinary <style> tag. Its contents will be generated at compile/build time and will result into some CSS (which apply to the entire document).
Unless specifically imported into the component SCSS, (using an #import command), the compiler will not know what $white means.
There is an important distinction to make between compilation context and browser context. Compilation happens at compile time (most likely in node-sass). Browser context is the actual browser, which only understands the CSS resulted from compilation.
How does Vue only apply style rules to the parent and not to the children with the same class? That's achieved by scoping.
It means applying a custom data-v-{key} attribute to all selectors in the generated <style> tag and to all elements the style should apply to.
See this example and inspect it using your web console: https://codesandbox.io/s/vue-template-ge2hb
It produces this markup:
As you can see, the scoped CSS has an extra [data-v-763db97b] added to the selector, which means it only applies to elements having that data attribute.

"lessify" a CSS color theme

I've inherited a project with a ton of CSS and been assigned the task of modifying it so the color palette can easily be changed.
I've immediately thought of using a CSS preprocessor, tried less and easily switched the colors for variables, so I just have to define a base color and can switch the color theme.
The problem is, every time I switch the color theme I have to either overwrite colors.less with the new color settings or modify the colors.less import in a ton of files.
What I want is to end up with a single file with a lot of imports (basically one per component or set of components), and on that file when I import colors-red.less instead of colors-blue.less all the components imported right after use the red palette so the theme compiled is red instead of blue, for example.
The problem I am having is that the component files do not get the "globals" with the color definitions so I can't compile the base file that imports those files.
I've read there is the possibility of using "partials" (files starting with _ that won't get compiled independently but imported and then compiled), but my compiler seems to be ignoring this feature, and the eclipse plugin I use for editing and verifying less files also complains about the color variables not being defined on those partials.
How can I can get the partials to work? Is there a better approach to do this task?
Stil, they won't be defined on the imported files, just on the main file, so >compilation will break on the imported files. You see what I mean?
Nope? example:
mixins.less:
.mixin()
{
color: #color;
}
variables.less:
#color: orange;
project.less:
#import "mixins";
#import "variables";
p {
.mixin();
}
Now running lessc project.less outputs:
p {
color:orange;
}
Now i change to content of project.less as follows:
#import "mixins";
#import "variables";
p {
.mixin();
}
#color: red;
Then running lessc project.less outputs:
p {
color:red;
}

Import css/scss file into a class

I have a problem. I'm using vaadin inside liferay. I've successfully written a fully responsive (yeah, tables too) theme for vaadin, based on bootstrap. Now I'm importing it to liferay. Everything went fine 'till I needed to upgrade Liferay, where their new responsive theme is using same classes name as bootstrap, but with different behaviour (sad, very sad face).
The solution I've thought so far is to apply a class to the vaadin compiled css, like:
.daVaadinTheme {
#import bootstrap.css;
}
so the content will be compiled like:
.daVaadinTheme h1.insideTheFile{
}
.daVaadinTheme h2.insideTheFile{
}
But, as you may figured out, is not obviously working.
Do you have any solution?
Read carefully! This is NOT a duplicate of the answer you've posted. I'm trying to import a CSS file inside a CSS/SCSS class of another file, like the example I've written above. My problem is not to simply import a CSS file inside another one...
SOLUTION: (kudos to Mathias Jørgensen)
using #import from another scss file:
in test.scss:
.daVaadinTheme{
#import "bootstrap.scss";
}
Name your inner file with an underscore, and ending in scss. .Yes, even if it's plain css, i.e. foo.css → _foo.scss
Have an outer File like so:
#main .content { // if that's, where you want them to rule only
#import 'foo';
}
Reasons:
import only works with scss
underscore-files are glady skipped by sass (also as in gulp.src(<some wildcards).sass())
if you have no influence in your repo about the css filename whatsoever. or it's a major pain on upgrades, consider using a symbolic link under an .scss extension...
You need move your code into mixin:
// botstrap.scss
#mixin bootstrap {
h1.insideTheFile{
}
h2.insideTheFile{
}
}
Then, you can import normal:
// test.scss
#import "bootstrap"; // No extension
#include bootstrap; // The name of "mixin"
or with context:
// test.scss
#import "bootstrap"; // No extension
.daVaadinTheme {
#include bootstrap; // The name of "mixin"
}
If you want to add certain styles to a class using sass/scss I think what you're looking for is
.myClass { #import bootstrap.css; }

SASS - use variables across multiple files

I would like to keep one central .scss file that stores all SASS variable definitions for a project.
// _master.scss
$accent: #6D87A7;
$error: #811702;
$warning: #F9E055;
$valid: #038144;
// etc...
The project will have a large number of CSS files, due to its nature. It is important that I declare all project-wide style variables in one location.
Is there a way to do this in SCSS?
You can do it like this:
I have a folder named utilities and inside that I have a file named _variables.scss
in that file i declare variables like so:
$black: #000;
$white: #fff;
then I have the style.scss file in which i import all of my other scss files like this:
// Utilities
#import "utilities/variables";
// Base Rules
#import "base/normalize";
#import "base/global";
then, within any of the files I have imported, I should be able to access the variables I have declared.
Just make sure you import the variable file before any of the others you would like to use it in.
This question was asked a long time ago so I thought I'd post an updated answer.
You should now avoid using #import. Taken from the docs:
Sass will gradually phase it out over the next few years, and
eventually remove it from the language entirely. Prefer the #use rule
instead.
A full list of reasons can be found here
You should now use #use as shown below:
_variables.scss
$text-colour: #262626;
_otherFile.scss
#use 'variables'; // Path to _variables.scss Notice how we don't include the underscore or file extension
body {
// namespace.$variable-name
// namespace is just the last component of its URL without a file extension
color: variables.$text-colour;
}
You can also create an alias for the namespace:
_otherFile.scss
#use 'variables' as v;
body {
// alias.$variable-name
color: v.$text-colour;
}
EDIT As pointed out by #und3rdg at the time of writing (November 2020) #use is currently only available for Dart Sass and not LibSass (now deprecated) or Ruby Sass. See https://sass-lang.com/documentation/at-rules/use for the latest compatibility
This answer shows how I ended up using this and the additional pitfalls I hit.
I made a master SCSS file. This file must have an underscore at the beginning for it to be imported:
// assets/_master.scss
$accent: #6D87A7;
$error: #811702;
Then, in the header of all of my other .SCSS files, I import the master:
// When importing the master, you leave out the underscore, and it
// will look for a file with the underscore. This prevents the SCSS
// compiler from generating a CSS file from it.
#import "assets/master";
// Then do the rest of my CSS afterwards:
.text { color: $accent; }
IMPORTANT
Do not include anything but variables, function declarations and other SASS features in your _master.scss file. If you include actual CSS, it will duplicate this CSS across every file you import the master into.
In angular v10 I did something like this, first created a master.scss file and included the following variables:
master.scss file:
$theme: blue;
$button_color: red;
$label_color: gray;
Then I imported the master.scss file in my style.scss at the top:
style.scss file:
#use './master' as m;
Make sure you import the master.scss at the top.
m is an alias for the namespace;
Use #use instead of #import according to the official docs below:
https://sass-lang.com/documentation/at-rules/import
Then in your styles.scss file you can use any variable which is defined in master.scss like below:
someClass {
backgroud-color: m.$theme;
color: m.$button_color;
}
Hope it 'll help...
Happy Coding :)
Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:
#import 'base/_reset';
#import 'helpers/_variables';
#import 'helpers/_mixins';
#import 'helpers/_functions';
#import 'helpers/_helpers';
#import 'helpers/_placeholders';
#import 'base/_typography';
#import 'pages/_versions';
#import 'pages/_recording';
#import 'pages/_lists';
#import 'pages/_global';
#import 'forms/_buttons';
#import 'forms/_inputs';
#import 'forms/_validators';
#import 'forms/_fieldsets';
#import 'sections/_header';
#import 'sections/_navigation';
#import 'sections/_sidebar-a';
#import 'sections/_sidebar-b';
#import 'sections/_footer';
#import 'vendors/_ui-grid';
#import 'components/_modals';
#import 'components/_tooltip';
#import 'components/_tables';
#import 'components/_datepickers';
And you can watch them with gulp/grunt/webpack etc, like:
gulpfile.js
// SASS Task
var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('styles', function(){
return gulp
.src('sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./build/css/'));
});
gulp.task('watch', function () {
gulp.watch('sass/**/*.scss', ['styles']);
});
gulp.task('default', ['watch']);
As previously mentioned, the use of #import is discouraged in newer versions of SASS. Use #use "path to SASS partial file" at the top of your file instead.*
You need to import (using #use) the partial SASS file into each SASS file that uses it - not just your main one.
Let's say we have a SASS file called _variables.scss* in a folder called partials that we want to use in header.scss. So in header.scss you write:
#use "partials/variables" as *
Now you can use all the variables defined in _variables.scss* with $variable (no prefix). Alternatively, you can use a namespace (like Christian already mentioned)
#use "partials/variables" as v
to refer to the variables inside _variables.scss* with v.$variable.
* Note that the SASS compiler ignores underscores so that there isn't a separate CSS file generated for each partial SASS file. Instead you can just import them all into your main SASS file with #use.
How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:
// base.scss
#import "./_variables.scss";
.background-color{
background: $bg-color;
}
and then, we can use the background-color class in any file.
My point is that I don't need to import variable.scss in any file, just use it.
I found a solution for vue3 using vite. If you are using dart-sass, you can get around the global limitation of sass modules by using #forward and #use.
_master.scss
$accent: #6D87A7;
$error: #811702;
$warning: #F9E055;
$valid: #038144;
// etc...
_global.scss
#forward '_master.scss';
// etc...
Then under the vite.config.js configure your css options as
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `
#use "./<path-to-file>/_globals.scss" as *;
`,
},
},
},
// etc...
});
As mentioned in the sass docs when importing modules without a namespace
We recommend you only do this for stylesheets written by you, though; otherwise, they may introduce new members that cause name conflicts!
You can then use other #use modules in any other stylesheets or components as following
// component file needing a function module
#use 'functions.scss';

Resources