react配置less,并使用less module(webpack.config.js配置)
网上看了很多配置,最后才发现create-react-app2.0后就不用eject就可以使用css module特性,那么less仿照css的配置即可
1.css module的使用
将CSS文件名为[filename].module.css
import styles from './index.module.css';
2.配置less
- 暴露webpack配置文件
cnpm run eject
安装lessless-loader依赖
npm install less less-loader --save-dev
- 修改webpack.config.js文件配置,一共修改三处
第一处:增加定义变量 ``` const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/; const lessRegex = /\.less$/; const lessModuleRegex = /\.module\.less$/; ``` 第二处:仿照css配置less ``` { test: cssRegex, exclude: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction && shouldUseSourceMap, }), // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, }, // Adds support for CSS Modules (https://github.com/css-modules/css-modules) // using the extension .module.css { test: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent, }), }, // Opt-in support for SASS (using .scss or .sass extensions). // By default we support SASS Modules with the // extensions .module.scss or .module.sass { test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction && shouldUseSourceMap, }), // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, }, // Adds support for CSS Modules (https://github.com/css-modules/css-modules) // using the extension .module.css { test: lessModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent, }), }, ``` 第三处:修改getCSSModuleLocalIdent函数内部,增加less ![图片描述][2]
3测试是否安装成功
- 建立以module.less为结尾的less文件
通过module引入less到index
import styles from './my.module.less' render() { console.log(styles.text) return ( <div> <div className={styles.text}>Hello World</div> </div> ) }
相关推荐
waterv 2020-07-18
qiupu 2020-11-04
多读书读好书 2020-11-03
RedCode 2020-10-28
jiedinghui 2020-10-25
Ladyseven 2020-10-22
hellowzm 2020-10-12
zuncle 2020-09-28
Ladyseven 2020-09-11
jiedinghui 2020-09-07
xiaohuli 2020-09-02
葉無聞 2020-09-01
impress 2020-08-26
ThikHome 2020-08-24
nicepainkiller 2020-08-20
hellowzm 2020-08-18