2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Sassの@useで何が変わったか

Posted at

@useって何?

2019年にSassに新たに導入されたモジュールシステムに @import の代わりとなる @use というルールが登場しました。 @use の使用によって、他のファイルで定義した CSS変数、関数、ミックスインを名前空間をつけて呼び出すことができます。

@use "variables";

.element {
  background-color: variables.$body-bg;
}

@importとの違い

名前空間をつける以外にも以下の点で挙動の違いがあります。

  • @use で読み込んだ変数等は読み込んだファイルでしか使えない
  • -_ で始まる変数等はPrivate Membersとなり宣言したファイルでしか使用できない

@use を使えばグローバル空間を汚染せずにすみそうですね。

名前空間をつけるメリット

改めて、Sassで名前空間をつけるメリットとしては

同じ名前で変数を定義した場合でも独立した変数として扱うことができる

事ですね。

それでは最初に、名前空間をつけない場合( @import で読み込んだ場合)を見ていきます。

// _follow-button-component.scss
$width: 100px;

// _like-button-component.scss
$width: 80px;
// style.scss
@import 'follow-button-component';
@import 'like-button-component';

.follow-button {
    width: $width; // 80px
}

.like-button {
    width: $width; // 80px
}

名前空間をつけないと、後から定義した変数のみ使用されるようになります。

これに対して、名前空間をつける場合( @use で読み込んだ場合)は、

// style.scss
@use 'follow-button-component';
@use 'like-button-component';

.follow-button {
    width: follow-button-component.$width; // 100px
}

.like-button {
    width: like-button-component.$width; // 80px
}

それぞれ定義した変数を使用することが出来きます。

上記のコードを見て分かるとおり、変数を定義したファイル名が名前空間になっています。

ファイル読み込み時に as を使えば好みの名前空間に変更できるので、ファイル名が長くなった時など使用すると良いですね。

// style.scss
@use 'follow-button-component' as follow;
@use 'like-button-component' as like;

.follow-button {
    width: follow.$width; // 100px
}

.like-button {
    width: like.$width; // 80px
}

Private Members

名前空間をつける以外にも、変数等をプライベートメンバーにする機能が追加されました。

名前の最初に-_ を付けることでプライベートメンバーになります。

プライベートメンバーは通常の変数のように使用することができますが、外部ファイルから読み込まれた時は参照できません。(参照した場合、コンパイルエラーが発生します。)

// _buttons.scss
$-btn-width: 10px;

.btn {
  width: $-btn-width; // 10px
}
// style.scss
@use "buttons";

.btn {
  width: $-btn-width;
	// This is an error! $-btn-width isn't visible outside of `_buttons.scss`.
}

まとめ

@use を使うことで変数等の競合やモジュール間の依存関係の問題を解消することができます。

2022年には @import のサポートが終了するので、新規プロジェクトでは @use を使用した方が良いですね。

参考記事

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?