... { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader?modules&localIdentName=[name]-[hash:base64:5]' } ] }, ...
import React, { Component } from 'react'; // 將樣式文件當成模塊引入 import styles from "./test.css"; export default class Test extends Component { render() { return ( <div> <div className={styles.test}>測試</div> </div> ) } }
.test { color: red; }
以上就是CSS Modules的基本用法css
開啓CSS Modules以後默認的樣式都爲局部樣式html
// css 樣式 (:global)(.test1) { color: blue; } 或者以下(定義多個全局樣式) :global { .test1 { color: blue; } .test2 { color: red; } } // 全局樣式寫法和以前同樣 import React, { Component } from 'react'; import styles from "./test.css"; export default class Test extends Component { render() { return ( <div> <div className="test1">測試</div> </div> ) } }
// 樣式文件 .base { font-size: 20px; } .normal { composes: base; color: #333; } .disabled { composes: base; color: #ddd; } // 組件中 import React, { Component } from 'react'; import styles from "./test.css"; export default class Test extends Component { render() { return ( <div> <div className="normal">測試</div> </div> ) } } // 編譯後的html文件 <d class="div--base-daf62 div--normal-abc53">測試</div> // 因爲在 .normal 中 composes 了 .base,編譯後會 normal 會變成兩個 class。
import classNames from 'classnames'; import styles from './dialog.css'; export default class Dialog extends React.Component { render() { const cx = classNames({ [styles.confirm]: !this.state.disabled, [styles.disabledConfirm]: this.state.disabled }); return <div className={styles.root}> <a className={cx}>Confirm</a> ... </div> } }
// 組件中 ... return ( <div data-role='test'> 測試 </div> ) ... // 樣式 [data-role="test"] { color: red; }
import Component from './view/Component' // 全局樣式 import './styles/app.scss'; // 如下爲組件相關樣式(局部樣式) import './Component.scss';
module: { loaders: [{ test: /\.jsx?$/, loader: 'babel' }, { test: /\.scss$/, exclude: path.resolve(__dirname, 'src/styles'), loader: 'style-loader!css-loader?modules&localIdentName=[name]__[local]!sass?sourceMap=true' }, { test: /\.scss$/, include: path.resolve(__dirname, 'src/styles'), loader: 'style-loader!css-loader!sass-loader?sourceMap=true' }] }