作成日:2024-03-28, 更新日:2024-03-28
現状とやりたいこと
現状
- 「common.scss」が存在する
- 「#hoge .foo{}」の設定が存在する
やりたいこと
- 「common.scss」を触らない
- 「common.scss」にある「#hoge .foo{}」の設定を「#bar .foo{}」に設定したい
common.scss
#hoge { .foo { /* 省略 */ } .xxx { /* 省略 */ } }
出来ること、出来ないこと
まず…出来ないっぽい。子要素がいると複雑…ってことでダメらしい
出来ること: 「common.scss」にある「#hoge{}」の設定を「#bar{}」に設定する場合
▼new_common.scssを用意(ファイル名は任意)
@import common #bar { @extend #hoge; }
出来ないこと: 「common.scss」にある「#hoge .foo{}」の設定を「#bar .foo{}」に設定する場合
▼「@extend #hoge .foo」がダメらしい。ビルドすると「complex selectors may not be extended.」というエラーになる
@import common #bar { .foo { @extend #hoge .foo; } }
妥協案
- 「common.scss」を修正して、@mixin、@includeで対応
- 「#hoge{}」を継承して、「#hoge .foo{}」以外の「#hoge xxx{}」の設定も受け入れる
「common.scss」を修正して、@mixin、@includeで対応
▼「common.scss」に@mixin、@includeを追加
@mixin style-foo { /* 省略 */ } #hoge { .foo { /* @include style-foo; */ } .xxx { /* 省略 */ } }
▼new_common.scssを用意(ファイル名は任意)
@import common #bar { .foo { @include style-foo;; } }
「#hoge{}」を継承して、「#hoge .foo{}」以外の「#hoge xxx{}」の設定も受け入れる
「#hoge{}」を継承して「#bar」を用意した場合、「#bar .foo{}」は欲しい。「#bar .xxx{}」はいらない…となるんだけど「#bar .xxx{}」の記述があっても問題ないと思われる
今回のようなケースだと基本的に「#bar .foo」なHTMLしか作らないと思うので「#bar .xxx{}」がいてもデザイン的に問題は起きない…はず
ただ、CSSファイルの容量が少し増える…という問題がある