angularsassmixinscss-variables

Global import and use of mixins file in Angular


is there a way to create global mixins.scss file in src/assets/style/mixins.scss and be able to use it in every component style sheet without importing it all the time? For the moment I managed to set up global CSS variable file that i decorated with :root

   colors.scss
   root: {
   --primary-white: #FFFFF 
   }
   
   mixins.scss
   root: {
   @mixin my-mixin: linear-gradient(#07347C, #1767AD) 
   }
   

then I can use it in my component file directly without importing it because I have already imported this file in my global stylesheet styles.scss.

  // styles.scss
  
  @import 'src/assets/styles/colors.scss
  @import 'src/assets/styles/mixins.scss

  
 // componentStyle.scss 
  
 button {
 @include my-mixin -- this doesn't work
 }
  
 .toolbar {
    background-color: var(--primary-white) -- this works
  }

I then created mixins file on the same principle but if I import it in my global scss file I still need to import it in my component scss file.

Is there a way to create global mixins file just like I did with CSS variables and use it everywhere in my application without having to import it every time.

Thank you!


Solution

  • Short answer: No. Each SCSS file need to import the mixins.scss (name is up to you) which includes the specific scss.

    If you have multiple files, you can create one all-mixins.scss which imports all other scss files and then you need only to import this own all-mixins-scss in your components. But the @import is needed.

    Workarounds

    You can write a build script. Example:

    // add-imports.js
    const glob = require("glob");
    const fs = require("fs");
    
    const files = glob.sync("./src/app/**/*.scss");
    const importStatement = '@import "path/to/your/mixins";\n';
    
    files.forEach(file => {
      const content = fs.readFileSync(file, "utf8");
      if (!content.startsWith(importStatement)) {
        fs.writeFileSync(file, importStatement + content, "utf8");
      }
    });
    

    Run this script before you start ng serve - it will be add the import of your file automatically.