0
0

More than 1 year has passed since last update.

[SASS] !defaultフラグ について整理

Last updated at Posted at 2023-01-14

今までスルーしてきましたが業務内でこれらに向き合う必要が出てきたので、自分用に整理してみました。

!defaultとは

まずは公式ドキュメントから

Normally when you assign a value to a variable, if that variable already had a value, its old value is overwritten.

普通に書いたら変数宣言が重複した場合、新しく宣言した値で古い値は上書きされる

Sass provides the !default flag. This assigns a value to a variable only if that variable isn’t defined or its value is null. Otherwise, the existing value will be used.

!defaultフラグを付けることで、未定義か定義済みでも値がnullの場合に限り値を上書きすることが可能

簡単に動作確認してみました。

実例

!defaultなし

変数用のファイルvariables.scssをimportしたのち、同じ変数に値を代入した場合

variable.scss
$base-color: blue;

main.scss
@import "variable";
$base-color: red;

.testStyle{
  background: $base-color;
}

検証用のHTMLを適当に作成

index.html

<div style={styles}>
	<h1 className="testStyle">
    	Sass !default 検証
	</h1>
</div>

この時、背景は新しく宣言した赤になる。
Pasted image 20230114155359.png

!defaultあり

importした後に!defaultをつけて変数宣言した場合

variable.scss

$base-color: blue;

main.js
@import "variable";

$base-color: red !default;

.testStyle{
  background: $base-color;
}

この時、背景はdefaultを付けて宣言した赤ではなく、最初に代入した青色になる。
Pasted image 20230114155605.png

色々見ていると、共通で適用するスタイル用変数を!defaultで宣言し、各画面毎に新しくスタイルを適用したい場合、変数をオーバーライドする という感じ。

以下は、一例。

common-variables.scss

$base-color: blue !default;
$sub-color: yellow !default;

page1.js

$base-color: red ;
@import "common-variables";

.h1{
  background: $base-color;
}

.h2{
  background: $sub-color;
}

この時、上書きした変数のみ変更される。

Pasted image 20230114162458.png

参考

Saas公式: https://sass-lang.com/documentation/variables

役に立ったという人がいれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0