Thanks @pengzeyacss
安裝less-watch-compiler到開發依賴。node
npm i less-watch-compiler --save-dev
添加scriptsreact
"scripts": { "build-css": "less-watch-compiler --run-once --main-file=index.less src/less src/css", "watch-css": "npm run build-css && less-watch-compiler --main-file=index.less src/less src/css" }
運行命令webpack
npm run watch-css
運行結果
建立css目錄並生成編譯後的index.css文件git
src/less/index.less → src/css/index.css
程序運行起來後,會監控對應目錄下的.less文件,熱更新到css目錄下。github
安裝node-sass-chokidar到依賴web
npm install --save node-sass-chokidar
添加scriptsnpm
"build-css": "node-sass-chokidar src/sass -o src/css", "watch-css": "npm run build-css && node-sass-chokidar src/sass -o src/css --watch --recursive",
運行命令sass
npm run watch-css
運行結果
建立css目錄並生成編譯後的index.css文件app
src/sass/index.scss → src/css/index.css
程序運行起來後,會監控對應目錄下的.scss文件,熱更新到css目錄下。
暴露出配置文件:
npm run eject
運行eject命令後,CRA會自動把wepack中與css-modules相關的依賴爲咱們準備好,無需新增多餘的依賴。
修改config/webpack.config.dev.js:
// 修改前 { loader: require.resolve('css-loader'), options: { importLoaders: 1, }, }, // 修改後 { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, localIdentName: "[name]__[local]___[hash:base64:5]" }, },
修改config/webpack.config.prod.js:
// 修改前 { loader: require.resolve('css-loader'), options: { importLoaders: 1, minimize: true, sourceMap: true, }, }, // 修改後 { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, minimize: true, sourceMap: true, }, },
代碼變化:
引入CSS Modules以前:
import React, { Component } from 'react'; import logo from './logo.svg'; import './foo.css'; class App extends Component { render() { return ( <div className="bar"> </div> ); } } export default App;
引入CSS Modules以後:
import React, { Component } from 'react'; import logo from './logo.svg'; import foo from './foo.css'; class App extends Component { render() { return ( <div className={foo.bar}> </div> ); } } export default App;
添加css-modules以前:
.bar{ display: block; background: yellow; }
添加css-modules以後:
.foo__bar__1t6eA{ display: block; background: yellow; }
運行結果
.bar → foo__bar__1t6eA
注意事項:
參考:
https://github.com/facebook/c...
https://github.com/facebook/c...
https://medium.com/nulogy/how...