In Ionic 2, I would like to access the $colors variables from the file \"[my project]\\src\\theme\\variables.scss\".
This file contains:
This is possible using 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 = '';
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:
- Export only the scss variables that you want to use.
- Configure a typescript module for
styles.scss.
- 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: