If you are working with single page web applications then it’s a common practise to separate out the css files and import it into the javascript file.
For example in react you would import the Css or Sass file into javascript file like this.
File : test.js
import ‘./Feedback.scss’;
It’s also common practise to import the css or scss(sass) files into other css files like the example below.
File : mystyles.css
@import ‘Global.sccs’
.className {
color:$grey
font-size: $label;
margin-top: 10px;
}
If you have a global css file, where you declare the variables like colors, font-sizes etc and which is imported at all the places in your other css or sass file make sure that you do not have any css classes defined in that global file.
For Eg:
Your Global.scss file has these contents where you have defined the application variables in sass.
—————-
$title: 35px;
$subtitle: 25px;
$label:20px;
$text: 15px;$red: red;
$grey:#4A4A4A;——————-
If you import this file in any of your other .scss file for example.
File name: newfile.scss
——————————–
@import ‘Global.sccs’
.className {
color:$grey
font-size: $label;
margin-top: 10px;
}
The above definitions work perfectly fine where your variables would be replaced with the values from global variables.
Now let us look at the example, where developers can go wrong.
In case you include any css classes into you Global.scss file like below.
body {
height:100%; // css definitions
}
@font-face {
font-family: ‘Times New Roman’, sans-serif; //css definition
}
$title: 35px;
$subtitle: 25px;
$label:20px;
$text: 15px;$red: red;
$grey:#4A4A4A;
Let us try to import the above global file into the new css file.
File name: test.scss
@import ‘Global.sccs’
.className {
color:$grey
font-size: $label;
margin-top: 10px;
}
When you build your application the above file would produce a CSS like this.
body {
height:100%;
}
@font-face {
font-family: ‘Times New Roman’, sans-serif;
}
.className {
color:#4A4A4A;
font-size: 20px;
margin-top: 10px;
}
You see that css definitions defined in the global file is also imported into the test.scss file.
If you start including the Global.scss files into every file, it will import the css definitions in all those files. Hence, your bundle in the end will have duplications of css defintions.
How to solve this ?
The better way to solve this is to import the Global.scss which contains the css definitions inside your application entrypoint only once. For example, in your index.js or app.js. This will ensure that the global.scss file is available to all the other sub files or to the entire application.
You can still import the Global.scss files into all the scss files, but it is necessary to ensure that the Global.scss file should just contain the sass variables or mixins. The sass builder will snot include the mixins into the final bundle and hence there is no duplications.