你的 css 也需要模塊化

uu4840 7年前發布 | 11K 次閱讀 CSS 前端技術

css “局部”樣式

sass、less 通過 @import ,部分解決的 css 模塊化的問題。

由于 css 是全局的,在被引入的文件和當前文件出現重名的情況下,前者樣式就會被后者覆蓋。

在引入一些公用組件,或者多人協作開發同一頁面的時候,就需要考慮樣式會不會被覆蓋,這很麻煩。

// file A
.name {
    color: red
}

// file B @import "A.scss"; .name { color: green }</code></pre>

css 全局樣式的特點,導致 css 難以維護,所以需要一種 css “局部”樣式的解決方案。

也就是徹底的 css 模塊化, @import 進來的 css 模塊,需要隱藏自己的內部作用域。

CSS Modules 原理

通過在每個 class 名后帶一個獨一無二 hash 值,這樣就不有存在全局命名沖突的問題了。這樣就相當于偽造了“局部”樣式。

// 原始樣式 styles.css
.title {
  color: red;
}

// 原始模板 demo.html import styles from 'styles.css';

<h1 class={styles.title}> Hello World </h1>

// 編譯后的 styles.css .title_3zyde { color: red; }

// 編譯后的 demo.html <h1 class="title_3zyde"> Hello World </h1></code></pre>

webpack 與 CSS Modules

webpack 自帶的 css-loader 組件,自帶了 CSS Modules,通過簡單的配置即可使用。

{
    test: /\.css$/,
    loader: "css?modules&localIdentName=[name]__[local]--[hash:base64:5]"
}

命名規范是從 BEM 擴展而來。

  • Block: 對應模塊名 [name]

  • Element: 對應節點名 [local]

  • Modifier: 對應節點狀態 [hash:base64:5]

使用 __ 和 -- 是為了區塊內單詞的分割節點區分開來。

最終 class 名為 styles__title--3zyde 。

在生產環境中使用

在實際生產中,結合 sass 使用會更加便利。以下是結合 sass 使用的 webpack 的配置文件。

{
    test: /\.scss$/,
    loader: "style!css?modules&importLoaders=1&localIdentName=[name]__[local]--[hash:base64:5]!sass?sourceMap=true&sourceMapContents=true"
}

通常除了局部樣式,還需要全局樣式,比如 base.css 等基礎文件。

將公用樣式文件和組件樣式文件分別放入到兩個不同的目標下。如下。

.
├── app                      
│   ├── styles               # 公用樣式
│   │     ├── app.scss       
│   │     └── base.scss      
│   │
│   └── components           # 組件
          ├── Component.jsx  # 組件模板
          └── Component.scss # 組件樣式

然后通過 webpack 配置,將在 app/styles 文件夾的外的(exclude) scss 文件"局部"化。

{
    test: /\.scss$/,
    exclude: path.resolve(__dirname, 'app/styles'),
    loader: "style!css?modules&importLoaders=1&localIdentName=[name]__[local]--[hash:base64:5]!sass?sourceMap=true&sourceMapContents=true"
},
{
    test: /\.scss$/,
    include: path.resolve(__dirname, 'app/styles'),
    loader: "style!css?sass?sourceMap=true&sourceMapContents=true"
}

有時候,一個元素有多個 class 名,可以通過 join(" ") 或字符串模版的方式來給元素添加多個 class 名。

// join-react.jsx
<h1 className={[styles.title,styles.bold].join(" ")}>
  Hello World
</h1>

// stringTemp-react.jsx <h1 className={${styles.title} ${styles.bold}}> Hello World </h1></code></pre>

如果只寫一個 class 就能把樣式定義好,那么最好把所有樣式寫在一個 class 中。

所以,如果我們使用了多個 class 定義樣式,通常會帶一些一些邏輯判斷。這個時候寫起來就會麻煩不少。

引入 classnames ,即可以解決給元素寫多個 class 名的問題,也可以解決寫邏輯判斷的麻煩問題。

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'</code></pre>

引入 CSS Modules 的樣式模塊,每個 class 每次都要寫 styles.xxx 也是很麻煩,在《深入React技術棧》提到了 react-css-modules 的庫,來減少代碼的書寫,感興趣的同學可以研究下。

參考資料:

《深入React技術棧》

css-modules

CSS Modules 用法教程

 

來自:https://segmentfault.com/a/1190000008064468

 

 本文由用戶 uu4840 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!