to use less files in a react project created with create-react-app follow these steps: npm run eject; npm i less less-loader ...
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Using.lessfileswithReact
AskQuestion
Asked
2years,9monthsago
Modified
12daysago
Viewed
40ktimes
17
7
Iamtryingtouse.lessfileswithaminimalistReactapp(createdwithcreate-react-app).I'veaddedlessandless-loadertomypackage.jsonaswellasamoduleruleinmywebpack.config.jsfile.TheclassreferenceisnotbeingaddedtotheHTMLelementhowever(shouldhaveclass="customColor").
Helloworldinacustomcolor.
I'mwonderingwhatI'mdoingwrong.
App.js
importReactfrom'react';
import'./App.css';
importstylesfrom'./custom.less';
functionApp(){
return(
Helloworldinacustomcolor.
);
}
exportdefaultApp;
custom.less
@custom-color:red;
.customColor{
color:@custom-color;
}
package.json
{
"name":"sample",
"version":"0.1.0",
"private":true,
"dependencies":{
"react":"^16.9.0",
"react-dom":"^16.9.0",
"react-scripts":"3.1.1"
},
"scripts":{
"start":"react-scriptsstart",
"build":"react-scriptsbuild",
"test":"react-scriptstest",
"eject":"react-scriptseject"
},
"eslintConfig":{
"extends":"react-app"
},
"devDependencies":{
"less":"^3.10.3",
"less-loader":"^5.0.0"
}
}
webpack.config.js
module.exports={
rules:[{
test:/\.less$/,
use:[{
loader:'style-loader',
},{
loader:'css-loader',//translatesCSSintoCommonJS
},{
loader:'less-loader',//compilesLesstoCSS
}],
}],
}
reactjsless
Share
Improvethisquestion
Follow
askedSep1,2019at21:46
JoePJoeP
42911goldbadge44silverbadges1111bronzebadges
3
AssumingyouareusingCRAv2youneedtoejectfirstthenmodifythewebpack.config.jsfile
– EdwardChopuryan
Sep1,2019at22:58
AlternativelyyoucantryforkingCRAauth0.com/blog/how-to-configure-create-react-app
– Rikin
Sep1,2019at23:52
Ok,Irannpmrunejectbutitdidn'tfixtheissue.IthinkIwasmissingamoduleattributeinwebpack.config.js,soIaddedit.Stillnotworkingthough...mywebpack.config.jsfilelookslikethisnow:module.exports={module:{rules:[....
– JoeP
Sep2,2019at3:39
Addacomment
|
6Answers
6
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
13
touselessfilesinareactprojectcreatedwithcreate-react-appfollowthesesteps:
npmruneject
npmilessless-loader
openwebpack.config.jsfilelocatedatconfigfoldercreatedafterejectscript:
lookatthereturnvalueofexportedfunction(that'sthemainconfig)
findwherelaststyle-loaderaddedwhichissass-loader
{
test:sassModuleRegex,
use:getStyleLoaders(
{
importLoaders:3,
sourceMap:isEnvProduction&&shouldUseSourceMap,
modules:{
getLocalIdent:getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
andaddless-loaderundersass-loaderlikethis:
{
test:sassModuleRegex,
use:getStyleLoaders(
{
importLoaders:3,
sourceMap:isEnvProduction&&shouldUseSourceMap,
modules:{
getLocalIdent:getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
{
test:/\.less$/,
use:getStyleLoaders(
{
modules:true,
importLoaders:3,
sourceMap:isEnvProduction&&shouldUseSourceMap,
},
'less-loader'
),
//Don'tconsiderCSSimportsdeadcodeevenifthe
//containingpackageclaimstohavenosideeffects.
//Removethiswhenwebpackaddsawarningoranerrorforthis.
//Seehttps://github.com/webpack/webpack/issues/6571
sideEffects:true,
},
importLoadersoptioninsideless-loadershouldbe3.
twoloadersfromgetStyleLoaders+ourless-loader.
TheoptionimportLoadersallowsyoutoconfigurehowmanyloadersbeforecss-loadershouldbeappliedto@importedresources.
whymoduleoptionistrue?
//index.lessfile
.header{
background-color:skyblue;
}
ifyouwanttousestylesheetfilelikethis:
importstylesfrom'./index.less';
youshouldsetmodules:true
butifyouwanttouseitlikebelow:
import'./index.less';
youshouldsetmodules:false
Share
Improvethisanswer
Follow
editedOct19,2020at3:44
answeredOct15,2020at11:38
arminyahyaarminyahya
1,23666silverbadges1414bronzebadges
3
WelcometoStackOverflow.Pleasedon'tjustpostsometoolorlibraryasananswer.Atleastdemonstratehowitsolvestheproblemintheansweritself.Link-onlyanswerscanbecomeinvalidifthelinkedpagechangesandanswersthatarelittlemorethanalinkmaybedeleted.
– fcdt
Oct15,2020at15:04
2
Thisisanexcellentanswerandclearlysavedmedaysofsearching.Thankyouverymuchforthedetailandtheexplanations.Superuseful!
– rushkeldon
Jan5,2021at8:08
Anythingthatrequirestoejectisaninstantdownvote.Thisisobviouslyanissueencountered1)byabeginner,2)intheearlystageoftheproject.TwoverygoodreasonsNOTtoeject.
– SzczepanHołyszewski
Apr3at18:38
Addacomment
|
7
Ifyou'reusingCRA,Iwouldsuggestgoingwithoutejecting.
Firstinstallless,less-watch-compilerandconcurrently:
npminstalllessless-watch-compilerconcurrently--save-dev
Theninyourrootdirectorycreateless-watcher.config.jsonandsettheconfiguration:
{
"watchFolder":"src/",
"outputFolder":"src/",
"runOnce":false,
"enableJs":true
}
RenameApp.csstoApp.less
Replacestartscriptinpackage.jsonwiththefollowing:
"scripts":{
"start":"concurrently--kill-others\"less-watch-compiler--configless-watcher.config.json\"\"react-scriptsstart\"",
"build":"react-scriptsbuild",
....
}
andruntheapplication.Enjoy:)
Share
Improvethisanswer
Follow
answeredMar17,2021at16:27
MaksymKoshykMaksymKoshyk
38844silverbadges66bronzebadges
Addacomment
|
3
CRA(CreateReactApp)bydefaultsupportsonlySASSandCSSifyouwanttouseLESSyouneedtodonpmrunejectfirstandthenmodifywebpackconfigs.
Howeverthereisawaytodothatw/oejectingthoIhavetosayIpersonallypreferejecting.Youcanfindinstructionshere
Share
Improvethisanswer
Follow
answeredSep1,2019at23:03
EdwardChopuryanEdwardChopuryan
28311silverbadge88bronzebadges
Addacomment
|
0
Try:
{test:/\.less$/,use:['style-loader','css-loader','less-loader']}
Share
Improvethisanswer
Follow
editedMay19,2020at18:04
PaulRoub
35.8k2727goldbadges7979silverbadges8888bronzebadges
answeredMay19,2020at18:01
NickChenNickChen
1
Addacomment
|
0
Afterupgradingmyreacttov18youcandoitwithreact-app-rewiredlibrarywithoutejectingyourwholeconfigofreact,it'smorecleaner.
installreact-app-rewired
npmireact-app-rewired
installlessandlessloader
npminstalllessless-loader--save-dev
changeyourscriptsinpackage.jsonto
"start":"react-app-rewiredstart",
"build":"react-app-rewiredbuild",
"test":"react-app-rewiredtest",
afterthatyouneedafilenamedconfig-overrides.jstoconfig
afterreadingthewebpackconfigofreactappiunderstoodthat
module.exports=functionoverride(config,env){
config.module.rules[1].oneOf.splice(2,0,{
test:/\.less$/i,
exclude:/\.module\.(less)$/,
use:[
{loader:"style-loader"},
{loader:"css-loader"},
{
loader:"less-loader",
options:{
lessOptions:{
javascriptEnabled:true,
},
},
},
],
})
returnconfig
}
andthat'sit.
Share
Improvethisanswer
Follow
answeredMay26at11:34
KaliforniumKalifornium
69377silverbadges1010bronzebadges
Addacomment
|
-1
Isitrelevanttousethismethodinlargeprojects?
npmruneject
npmilessless-loader
openwebpack.config.jsfilelocatedatconfigfoldercreatedafterejectscript:
lookatthereturnvalueofexportedfunction(that'sthemainconfig)
findwherelaststyle-loaderaddedwhichissass-loader
{
test:sassModuleRegex,
use:getStyleLoaders(
{
importLoaders:3,
sourceMap:isEnvProduction&&shouldUseSourceMap,
modules:{
getLocalIdent:getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
{
test:/\.less$/,
use:getStyleLoaders(
{
modules:true,
importLoaders:3,
sourceMap:isEnvProduction&&shouldUseSourceMap,
},
'less-loader'
),
//Don'tconsiderCSSimportsdeadcodeevenifthe
//containingpackageclaimstohavenosideeffects.
//Removethiswhenwebpackaddsawarningoranerrorforthis.
//Seehttps://github.com/webpack/webpack/issues/6571
sideEffects:true,
},
Share
Improvethisanswer
Follow
answeredDec31,2021at22:20
AMGAMG
1
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedreactjslessoraskyourownquestion.
TheOverflowBlog
Remoteworkiskillingbigoffices.Citiesmustchangetosurvive
Onthequantuminternet,datadoesn’tstream;itteleports
FeaturedonMeta
AnnouncingthearrivalofValuedAssociate#1214:Dalmarus
Improvementstositestatusandincidentcommunication
CollectivesUpdate:IntroducingBulletins
The[comma]tagisbeingburninated
AskWizardTestResultsandNextSteps
Linked
0
Howtouseless.modifyVarsinReact?
Related
1747
LoopinsideReactJSX
1332
WhatarethesethreedotsinReactdoing?
2036
ProgrammaticallynavigateusingReactrouter
927
WhatisthedifferencebetweenReactNativeandReact?
4
LoadCSSmoduleinReactJS+Typescriptandreactrewired
3
react-i18nextgettingerrorAttemptedimporterror
1
.lessfilesnotgettingpickedupbyless-loader
0
./src/App.jsxAttemptedimporterror:'Routes'isnotexportedfrom'react-router-dom'
HotNetworkQuestions
Howtodrawbrackettreesintikz?
NumberofregistrantsforavirtualtalkIorganizedturnedouttobesmall,shouldInotifythespeakerbeforehand?
DefiningSurfacegravityofablackhole
CanIcheckinattheairportwithoutavisaasIintendtogetVisaonArrivalatmydestination?
IsmakingallOpportunityAttackshavedisadvantagegamebreakinginanyway?
I'mlookingforamangathathasagamedeveloperasthemaincharacter
Howtounderstand'conspire'inthissentence?
Whatisthepurposeofa"monitordiode",insidealaserdiodecase?
Makealistflat
BIP-341:Shouldkey-path-onlyP2TRbeeschewedaltogether?
howtocombineverticesintoasurface
Whatnumbershouldthefirstpersonannounce?
CoefficientsreturnedfromCoefficientRules
IsitpossibletohaveaNewtonianuniversebuteverythingelsebehavethesamewayasthisuniverse?Whatadjustmentstophysicsisnecessary?
Whichfeatismostlikelytoboostwizardsurvival?
IsitpossibleformetogetanideaofwhatmyELOmightbe,outofcuriosity,withoutjoininganorganizationoranything?
Whatdoes"twice"meanin"Oncebitten,twiceshy"?
Howadd1inmathexpressioninsideTikZ\foreachloop
isitraretoelidethefinalvowelifitislong?
Whatwouldanalienspaceshipneedtohavetobeundetectabletouswithourcurrenttechnology
Isitconsideredrudeorinappropriatetofrequentlyaddressothersas"friend"-ofteninadisingenuousfashion?
WillIbebarredfromtravelingtotheUSinthefuture,afteratenseimmigrationinterrogation?
Whenwesayarigidbodyisasystemofparticles,whatexactlyare'particles'here?
AregunsthenumberonekillerofchildrenintheUS?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-js
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings