Sassの@importの問題点を理解する。

@importは廃止されます

@importを使って別ファイルを読み込む方法を変える必要があります。
下記、公式サイトにも書かれている通り、今後廃止されます。

The Sass team discourages the continued use of the @import rule. Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead. (Note that only Dart Sass currently supports @use. Users of other implementations must use the @import rule instead.)

では@importはなぜ廃止されるのか。
理由がいくつかありますので確認します。

グローバル汚染問題

- @import makes all variables, mixins, and functions globally accessible. This makes it very difficult for people (or tools) to tell where anything is defined.
- Because everything’s global, libraries must prefix to all their members to avoid naming collisions.
- @extend rules are also global, which makes it difficult to predict which style rules will be extended.
- There was no way to define private members or placeholder selectors that were inaccessible to downstream stylesheets.

下記のような読み込みをした場合A.scssで定義した変数やmixin、関数はB.scssはもちろん、C.scssでも使用する事ができます。

// A.scss
$color: black;

// B.scss
@import A.scss
background-color: $color; // OK

// C.scss
@import B.scss
background-color: $color; // OK

使い回しが効くので一見便利ですが、一定の規模に膨れ上がったり、保守期間がながくなると使用している変数・関数・mixinがどのファイルで定義されたものかわかりづらくコストが増大するリスクが発生します。

ですが、正直一般的なWebサイトを制作する身としては特に困る事はなく、逆に扱いやすいくらいです。

コンパイル時間が長くなる問題

Each stylesheet is executed and its CSS emitted every time it’s @imported, which increases compilation time and produces bloated output.

これはシンプルに解決されるべき問題だと思います。
ただ個人の感想ですが、待たされるほど大きなCSSを書く事はあまり経験がありません。
少し前までBootstrap4をベースにサイト個別のコンポーネントやユーティリティの為のCSSを追加するような書き方をしていましたが、1-2秒かかるかどうか程度だったかと思います。
うりゃーっとコードを書いて確認まで一呼吸するのにちょうどいいくらいです。

まとめ

一般的なWebサイトを制作している分には@importで正直困る事はないです。@importが廃止されて次に使うべき@useの仕様はデザイナーやコーダーには少々わかりずらいと思います。@import廃止や@useはまさにエンジニアらしい観点で考えられた仕様だなと思います。
エンジニア思考はバグやメンテ効率化などの為に制約を増やしたがります。
正直面倒ですが、努力して理解する中で得られる事は@importやら@useやらの知識をつけるだけではなく、こういった思考に慣れていく事もできるのでこのメリットは大きいです。
がんばりましょう。

この記事が気に入ったらサポートをしてみませんか?