access SASS values ($colors from variables.scss) in Typescript (Angular2 ionic2) access SASS values ($colors from variables.scss) in Typescript (Angular2 ionic2) angular angular

access SASS values ($colors from variables.scss) in Typescript (Angular2 ionic2)


Unfortunately, there is no way to access SASS variable directly from typescript/javascript code. However, we can make a workaround to access those variables.

Let me describe briefly the steps to access SASS variables from within typescript source code:

1. Creating a SASS Helper Component

Create ../providers/sass-helper/sass-helper.component.scss:

$prefix: "--"; //Prefix string for custom CSS properties//Merges a variable name with $prefix@function custom-property-name($name) {    @return $prefix + $name;}// Defines a custom property@mixin define-custom-property($name, $value) {    #{custom-property-name($name)}: $value;}body {    // Append pre-defined colors in $colors:    @each $name, $value in $colors {        @include define-custom-property($name, $value);    }    // Append SASS variables which are desired to be accesible:    @include define-custom-property('background-color', $background-color);}

In this SCSS file, we simply create custom properties inside the body section of the DOM. You should add each SASS variable that you want to be accessible into this SCSS file by using the mixin called define-custom-property which expects two parameters: variable name and variable value.

As an example, I have added entries for all the colors defined in $colors as well as an entry for the SASS variable $background-color defined in my theme/variables.scss file. You can add as many variables as you wish.

Create ../providers/sass-helper/sass-helper.component.ts:

import { Component } from '@angular/core';export const PREFIX = '--';@Component({    selector: 'sass-helper',    template: '<div></div>'})export class SassHelperComponent {    constructor() {    }    // Read the custom property of body section with given name:    readProperty(name: string): string {        let bodyStyles = window.getComputedStyle(document.body);        return bodyStyles.getPropertyValue(PREFIX + name);    }}

2. Integrating SASS Helper Component

From now on, we can follow standard Ionic2 framework principles for component integration and usage.

  • Add the component class name (SassHelperComponent) into the declarations section of your NgModule in app.module.ts
  • Insert the following HTML code into the HTML template of your page from where you want to access those magic variables:

    <sass-helper></sass-helper>


3. Using Helper Component

In your page's TS file, you should insert the following lines into your page class:

@ViewChild(SassHelperComponent)private sassHelper: SassHelperComponent;

Finally, you can read the value of any SASS variable by just calling the child class method as follows:

// Read $background-color:this.sassHelper.readProperty('background-color');// Read primary:this.sassHelper.readProperty('primary');


One possibility is to generate a .ts file from the .scss file. A simple example of this process:

1) Install npm i --save-dev scss-to-json.

2) Put this in your package.json:

  "scripts": {    ...    "scss2json": "echo \"export const SCSS_VARS = \" > src/app/scss-variables.generated.ts && scss-to-json src/variables.scss >> src/app/scss-variables.generated.ts"  },

and run it with npm run scss2json. Windows users will need to adjust the example.

3) Access the variables:

import {SCSS_VARS} from './scss-variables.generated';...console.log(SCSS_VARS['$color-primary-1']);

One advantage of this is, that you'll get type completion from IDE's and it's a quite simple means to achieve your goal in general.

Of course you could make this more advanced, for example by making the generated file read only and by putting the script into it's own .js file and make it work on every OS.


This is possible using CSS Modules.

CSS Modules

From the project description:

When importing the CSS Module from a JS Module, it exports an object with all mappings from local names to global names.

In a way that we could read variables from css/scss file like this:

import styles from "./style.css";    element.innerHTML = '<div class="' + styles.className + '">';

Support for CSS Modules is already setup by default by the Angular CLI which uses Webpack configured with the css-loader.

The steps to make it work are:

  1. Export only the scss variables that you want to use.
  2. Configure a typescript module for styles.scss.
  3. Import the variables in your typescript components.

1 - Export the variables

In your styles.scss, use the keyword :export to export $colors. It seems that :export doesn't support exporting maps, only strings, so we have to create a mixin to convert a map into strings:

$colors: (  primary: #387ef5,  secondary: #32db64,  danger: #f53d3d,  light: #f4f4f4,  dark: #222,  favorite: #69bb7b,);@mixin rule($key, $value, $prefix) {  #{$prefix}-#{$key}: $value;}@mixin map-to-string($map, $prefix) {  @each $key, $value in $map {    @include rule($key, $value, $prefix);  }}:export {    @include map-to-string($colors, "colors");}

The generated :export will be:

:export {  "colors-danger": "#f53d3d";  "colors-dark": "#222";  "colors-favorite": "#69bb7b";  "colors-light": "#f4f4f4";  "colors-primary": "#387ef5";  "colors-secondary": "#32db64";}

2 - Configure a typescript module for styles.scss

We have to create a styles.scss.d.ts file with the following content to allow the import of styles.scss in our typescript files:

export interface globalScss {}export const styles: globalScss;export default styles;

3 - Import the variables in the target typescript component

As we used a default export, we could import it in our component like this:

//...import styles from 'src/styles.scss';@Component({  selector: 'app-colors-use',  templateUrl: './colors-user.component.html',  styleUrls: ['./colors-user.component.scss'],})export class ColorsUserComponent implements OnInit {  buttonColor = styles["colors-primary"] //"#387ef5"

4 - (Plus) Add type definition to styles.scss.d.ts

You could add type information to style.scss.d.ts:

export interface globalScss {    "colors-danger": string  "colors-dark": string  "colors-favorite": string  "colors-light": string  /**   * Used for app-button, usually blue   */  "colors-primary": string  /**   * Used for borders, usually green   */  "colors-secondary": string}export const styles: globalScss;export default styles;

In that way, you could have some benefits in an editor like VS code:

Comments

Auto complete

UPDATE:

The configuration above only works until ng 10. Css Modules configuration has changed considerably from ng 10 to ng 11.