React CSS模塊化的解決方案

一、BEM與命名空間來規範CSS

BEM(block-element-modifer)方法論 + 約定項目命名空間<component (c-), object(o-)>

參考:https://juejin.im/post/5b20e8e0e51d4506c60e47f5

二、webpack中使用local scope

參考:https://juejin.im/post/5b234e25e51d45588016caa0

配置:

// 在webpack中的css-loader中進行配置
{
    loader: 'css-loader',
    options: {
        modules: true, // 開啓模塊化
        localIdentName: '[local]__[name]--[hash:base64:5]'
    }
}

使用場景:

// index.css
:local .title {
    font-size: 30px;
    color: #333;
}

// other.css
:local .title {
    font-size: 15px;
    color: #999;
}

// index.js
import styles from './index.css';
import others from './other.css';

funciont createTitle(str) {
    var title = document.createElement('h1');
    title.appendChild(document.createTextNode(str));
    // styles.title  font-size: 30px;color: #333;
    title.setAttribute('class', styles.title);
    document.body.appendChild(title);
}

createTitle('Hi!');

// 注意點:
1. 使用 :local標識
2. 注意引入方式:import others from '' 不在時 import ''
3. 使用方式:“styles.title”、title.setAttribute('class', styles.title);
// 如果希望 選擇器中的某一部分仍然是“全局”的, 如下操縱
:local .title :global(.sub-title) { color: #666; }

三、使用styled-components來解決

參考:https://juejin.im/post/5b2351946fb9a00e5a4b4d79

安裝:styled-components

簡單來說,就是在你使用styled-components進行樣式定義的同時,你也就創建了一個React組件。來先看一下它基本語法:

import styled from 'styled-components';

const ListWrap = styled.ul`
    margin: 0;
    padding: 0;
`;

const Item = styled.li`
    margin: 10px 0;
    padding: 5px 15px;
    border-left: 3px solid #333;
    font-size: 16px;
    list-style: none;
    font-weight: bold;
`;

四、TS下使用typings-for-css-modules-loader + css-loader(0.x版本 or 1.x版本) 在webpack中配置

{
    loader: 'typings-for-css-modules-loader',
    options: {
        localIdentName: '[local]_[hash:base64:8]',
        modules: true,
        namedExport: true,
        camelCase: true,
        sass: true,
        sourceMap: false
    }
}

// 配置typings文件  與src 目錄同級 生成一個 聲明文件, 假設你用的時 sass
// typed-css-modules.d.ts
declare module '*.scss' {
    const content: any
    export = content
}

//tsconfig.json中 添加 "./typings" <可能需要安裝"@types/node">
"typeRoots": ["node", "node_modules/@types", "./typings"]

如果你用的是高版本的 css-loader  比如3.x版本的  要麼降低版本,要不改換上面的方案,遇到的錯誤:

https://segmentfault.com/q/1010000020143819

原因在於 typings-for-css-modules-loader 版本  沒有隨着css-loader的升級而升級

後續將繼續跟進這個問題,尋找最佳實踐

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章