web-dev-qa-db-ja.com

TypeScript(Angular2 ionic2)のSASS値(variables.scssの$ colors)にアクセスします

Ionic 2)で、ファイル「[my project]\src\theme\variables.scss」から$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);
    }

}

ご覧のとおり、このコードのある時点で形状の色が定義されています:context.fillStyle = 'blue'、代わりにcontext.fillStyle = '[variables.scss OBJECT].$colors.primary 'のようなものを使用したいと思います。

誰もがアイデアを持っていますか?

36
nyluje

残念ながら、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);
}

このSCSSファイルでは、DOMのbodyセクション内にカスタムプロパティを作成するだけです。 mixinと呼ばれるdefine-custom-propertyを使用して、このSCSSファイルにアクセスできるようにする各SASS変数を追加する必要があります。

例として、$colorsで定義されているすべてののエントリと、theme/variablesで定義されているSASS変数$background-colorのエントリを追加しました。 scssファイル。必要な数の変数を追加できます。

作成../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. SASSヘルパーコンポーネントの統合

これからは、標準のIonic2コンポーネントの統合と使用のためのフレームワークの原則に従うことができます。

  • コンポーネントクラス名(SassHelperComponent)をNgModule in app.module.tsの宣言セクションに追加します
  • これらのマジック変数にアクセスするページのHTMLテンプレートに次のHTMLコードを挿入します。

    <sass-helper></sass-helper>


3.ヘルパーコンポーネントの使用

ページのTSファイルで、次の行をページクラスに挿入する必要があります。

@ViewChild(SassHelperComponent)
private sassHelper: SassHelperComponent;

最後に、次のように子クラスメソッドを呼び出すだけで、SASS変数の値を読み取ることができます。

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

// Read primary:
this.sassHelper.readProperty('primary');
36
Mete Cantimur

1つの可能性は、生成.tsファイルから.scssファイルにすることです。このプロセスの簡単な例:

1)npm i --save-dev scss-to-jsonをインストールします。

2)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"
  },

npm run scss2jsonで実行します。 Windowsユーザーは例を調整する必要があります。

3)変数にアクセスします。

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

この利点の1つは、IDEからタイプ補完を取得できることです。これは、一般的に目標を達成するための非常に簡単な手段です。

もちろん、例えば、生成されたファイルを読み取り専用にし、スクリプトをそれ自身の.jsファイルに入れて、すべてのOSで動作させることにより、これをより高度にすることができます。

4
bersling

@ mete-cantimurの回答に何か付け加えたいと思います。

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);
  }
}

ヘルパーコンポーネントは、ボディスタイルを変更できませんでした。すべてを正しく設定しても、カスタムプロパティは保存されませんでした。

ボディスタイルを変更できるようにするために、encapsulation: ViewEncapsulation.Noneをコンポーネントに追加する必要がありました。

お役に立てれば。

3
yuva