在Create React App中启用Sass和Less的方法示例
关于创建create-react-app项目请查看:create-react-app的安装与创建。
关于在less和sass如何在create-react-app启用CSSModules,请查看我的上一篇文章:在CreateReactApp中使用CSSModules。
启用Sass语法编写CSS
create-react-app脚手架中已经添加了sass-loader的支持,所以只需要安装node-sass插件即可
安装node-sass插件
$npminstallnode-sass--save #或者 #$yarnaddnode-sass
用法:
编写sass文件:App.scss
.App{ text-align:center; &-logo{ animation:App-logo-spininfinite20slinear; height:40vmin; } }
在js文件中直接使用:改写App.js文件
importReact,{Component}from'react'; importlogofrom'./logo.svg'; import'./App.scss'; classAppextendsComponent{ render(){ return(
在浏览器中查看效果
运行项目,此时在浏览器中即可查看到logo图片在缓慢转动。
启用Less语法编写CSS
由于create-react-app脚手架中并没有配置关于less文件的解析,所以我们需要自己进行配置。需要安装的插件less,less-loader。
添加Less相关配置
在命令行运行npmruneject命令
此命令会将脚手架中隐藏的配置都展示出来,此过程不可逆
运行完成之后,打开config目录下的webpack.config.js文件,找到//stylefilesregexes注释位置,仿照其解析sass的规则,在下面添加两行代码
//添加less解析规则 constlessRegex=/\.less$/; constlessModuleRegex=/\.module\.less$/;
找到rules属性配置,在其中添加less解析配置
//Less解析配置 { test:lessRegex, exclude:lessModuleRegex, use:getStyleLoaders( { importLoaders:2, sourceMap:isEnvProduction&&shouldUseSourceMap, }, 'less-loader' ), sideEffects:true, }, { test:lessModuleRegex, use:getStyleLoaders( { importLoaders:2, sourceMap:isEnvProduction&&shouldUseSourceMap, modules:true, getLocalIdent:getCSSModuleLocalIdent, }, 'less-loader' ) }
此时配置完成,安装less和less-loader插件即可
$npminstalllessless-loader--save
用法
以下代码根据上面sass用法中的文件进行修改
编写less文件:App.less
.App{ text-align:center; &-logo{ animation:App-logo-spininfinite20slinear; height:40vmin; } }
在js文件中直接使用:改写App.js文件
importReact,{Component}from'react'; importlogofrom'./logo.svg'; import'./App.less'; classAppextendsComponent{ render(){ return(
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。