访问Typescript(Angular2 ionic2)中的SASS值($colors from variables.scss)
在Ionic 2中,我想访问文件“[my project]\src\theme\variables.scss”中的访问Typescript(Angular2 ionic2)中的SASS值($colors from variables.scss),angular,typescript,sass,ionic2,Angular,Typescript,Sass,Ionic2,在Ionic 2中,我想访问文件“[my project]\src\theme\variables.scss”中的$colors变量 此文件包含: $colors: ( primary: #387ef5, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, favorite: #69BB7B ); 在组件中,我绘制画布。看起来是这样的: import
$colors
变量
此文件包含:
$colors: (
primary: #387ef5,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222,
favorite: #69BB7B
);
在组件中,我绘制画布。看起来是这样的:
import {Component, Input, ViewChild, ElementRef} from '@angular/core';
@Component({
selector: 'my-graph',
})
@View({
template: `<canvas #myGraph class='myGraph'
[attr.width]='_size'
[attr.height]='_size'></canvas>`,
})
export class MyGraphDiagram {
private _size: number;
// get the element with the #myGraph on it
@ViewChild("myGraph") myGraph: ElementRef;
constructor(){
this._size = 150;
}
ngAfterViewInit() { // wait for the view to init before using the element
let context: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d");
// HERE THE COLOR IS DEFINED AND I D LIKE TO ACCESS variable.scss TO DO THAT
context.fillStyle = 'blue';
context.fillRect(10, 10, 150, 150);
}
}
从'@angular/core'导入{Component,Input,ViewChild,ElementRef};
@组成部分({
选择器:“我的图形”,
})
@看法({
模板:``,
})
导出类MyGraphDiagram{
私人_大小:数字;
//获取带有#myGraph的元素
@ViewChild(“myGraph”)myGraph:ElementRef;
构造函数(){
这个。_尺寸=150;
}
ngAfterViewInit(){//在使用元素之前,等待视图初始化
let context:CanvasRenderingContext2D=this.myGraph.nativeElement.getContext(“2d”);
//这里定义了颜色,我想访问variable.scss来实现这一点
context.fillStyle='blue';
fillRect(10,10,150,150);
}
}
正如大家所看到的,在这段代码的某个地方,形状的颜色被定义为:context.fillStyle='blue'
,我想使用类似于context.fillStyle='[variables.scss OBJECT].$colors.primary'
有人知道吗?不幸的是,无法直接从typescript/javascript代码访问SASS变量。但是,我们可以做一个变通方法来访问这些变量 让我简要描述从typescript源代码中访问SASS变量的步骤: 1.创建SASS帮助器组件 创建。/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);
}
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);
}
}
在这个SCSS文件中,我们只需在DOM的body部分中创建自定义属性。您应该使用名为define custom property
的mixin将希望访问的每个SASS变量添加到此SCSS文件中,该属性需要两个参数:变量名称和变量值
例如,我为$colors
中定义的所有颜色添加了条目,并为我的主题/variables.scss文件中定义的SASS变量$background color
添加了条目。您可以添加任意数量的变量
创建。/providers/sass-helper/sass-helper.component.ts:
$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);
}
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);
}
}
最后,只需调用子类方法即可读取任何SASS变量的值,如下所示:
// Read $background-color:
this.sassHelper.readProperty('background-color');
// Read primary:
this.sassHelper.readProperty('primary');
一种可能性是从
.scss
文件生成.ts
文件。此过程的一个简单示例:
1) 安装npmi--将dev scs保存到json
2) 将其放入您的包中。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"
},
并使用npm run scss2json
运行它。Windows用户需要调整示例
3) 访问变量:
import {SCSS_VARS} from './scss-variables.generated';
...
console.log(SCSS_VARS['$color-primary-1']);
这样做的一个优点是,您可以从IDE中获得类型完成,这是实现您的目标的一种非常简单的方法
当然,您可以使其更高级,例如,将生成的文件设置为只读,并将脚本放入自己的
.js
文件中,使其在每个操作系统上都能工作。我想为@mete cantimur answer添加一些内容
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
const PREFIX = '--';
@Component({
selector: 'app-styles-helper',
templateUrl: './styles-helper.component.html',
styleUrls: ['./styles-helper.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class StylesHelperComponent implements OnInit {
ngOnInit(): void {
}
readProperty(name: string): string {
const bodyStyles = window.getComputedStyle(document.body);
return bodyStyles.getPropertyValue(PREFIX + name);
}
}
我的助手组件无法修改身体样式。即使我正确设置了所有内容,自定义属性也没有被保存
我必须向组件添加enclosuration:viewenclosuration.None
,以便让它修改身体样式
希望这能有所帮助。在Windows中,我使用了以下摘自Bersling答案的内容
npm i --save-dev ruoqianfengshao/scss-to-json
npm i --save-dev node-sass
"scripts": {
...
"scss2json": "echo export const SCSS_VARS = > .\\src\\app\\scss-variables.generated.ts && scss-to-json .\\src\\app\\_variables.scss >> .\\src\\app\\scss-variables.generated.ts"
}
npm run scss2json
import {SCSS_VARS} from './scss-variables.generated';
...
console.log(SCSS_VARS['$color-primary-1']);
我知道这个问题已经有几年历史了,但我想我会分享我使用的解决方案。这是@mete cantimur答案的更简单版本,不需要设置任何额外的CSS样式表。它将读取页面上加载的样式
import {Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[css-helper]',
})
export class CssHelperDirective {
element: any;
constructor(_ref: ElementRef) {
this.element = _ref.nativeElement;
}
readProperty(name: string): string {
return window.getComputedStyle(this.element).getPropertyValue(name);
}
}
用法:
<div #primary css-helper class="primary"></div>
这是可能的使用CSS模块 CSS模块 从项目中: 从JS模块导入CSS模块时,它会导出一个对象,该对象包含从本地名称到全局名称的所有映射 我们可以这样从css/scss文件中读取变量:
import styles from "./style.css";
element.innerHTML = '<div class="' + styles.className + '">';
//...
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"
生成的:导出将是:
:export {
"colors-danger": "#f53d3d";
"colors-dark": "#222";
"colors-favorite": "#69bb7b";
"colors-light": "#f4f4f4";
"colors-primary": "#387ef5";
"colors-secondary": "#32db64";
}
2-为style.scss
我们必须创建一个包含以下内容的style.scss.d.ts
文件,以允许在我们的typescript文件中导入style.scss
:
export interface globalScss {}
export const styles: globalScss;
export default styles;
3-导入目标typescript组件中的变量
由于我们使用了默认导出,我们可以将其导入到组件中,如下所示:
import styles from "./style.css";
element.innerHTML = '<div class="' + styles.className + '">';
//...
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-(外加)将类型定义添加到styles.scss.d.ts
您可以将类型信息添加到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;
这样,您可以在VS代码这样的编辑器中获得一些好处:
更新:
以上配置仅在ng 10之前有效。Css模块配置已从ng 10更改为ng 11。如果使用Css变量(自定义属性),可以使用getComputedStyle
轻松获取它们。似乎是另一种解决方案。是的,但必须有一种更简单的方法。是的,我希望有一种更简单的方法,但请记住,SASS必须编译为CSS,因此,编译后所有变量定义都会丢失。直接从typescript代码访问SASS文件将是一种替代方法,但是,它需要解析和HTTP访问,这是另一个麻烦。还没有时间尝试它(优先级转移),但由于它已经获得了两次投票,其他用户似乎验证了它。感谢您的帮助@Mete Cantimur。我知道我会在某个时候使用你的输入。@Mete Cantimur,我最终实现了它,它工作了。谢谢(在确认的基础上进行投票)。我所做的唯一稍微不同的事情是将“sass helper.component.ts”和“sass helper.component.scss”重命名为“sass helper.ts”和“sass helper.scss”。在这样做之前,颜色不在