less-loader - npm

文章推薦指數: 80 %
投票人數:10人

A Less loader for webpack. Compiles Less to CSS.. Latest version: 11.0.0, last published: 21 days ago. Start using less-loader in your ... less-loader11.0.0 • Public • Published21daysagoReadmeExploreBETA1Dependency5,784Dependents60Versions less-loader ALessloaderforwebpack.CompilesLesstoCSS. GettingStarted Tobegin,you'llneedtoinstalllessandless-loader: npminstalllessless-loader--save-dev or yarnadd-Dlessless-loader or pnpmadd-Dlessless-loader Thenaddtheloadertoyourwebpackconfig.Forexample: webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ //compilesLesstoCSS "style-loader", "css-loader", "less-loader", ], }, ], }, }; Andrunwebpackviayourpreferredmethod. Options lessOptions additionalData sourceMap webpackImporter implementation lessOptions Type: typelessOptions=import('less').options|((loaderContext:LoaderContext)=>import('less').options}) Default:{relativeUrls:true} YoucanpassanyLessspecificoptionstotheless-loaderthroughthelessOptionspropertyintheloaderoptions.SeetheLessdocumentationforallavailableoptionsindash-case.Sincewe'repassingtheseoptionstoLessprogrammatically,youneedtopassthemincamelCasehere: object UseanobjecttopassoptionsthroughtoLess. webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ { loader:"style-loader", }, { loader:"css-loader", }, { loader:"less-loader", options:{ lessOptions:{ strictMath:true, }, }, }, ], }, ], }, }; function AllowssettingtheoptionspassedthroughtoLessbasedoffoftheloadercontext. module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ lessOptions:(loaderContext)=>{ //Moreinformationaboutavailablepropertieshttps://webpack.js.org/api/loaders/ const{resourcePath,rootContext}=loaderContext; constrelativePath=path.relative(rootContext,resourcePath); if(relativePath==="styles/foo.less"){ return{ paths:["absolute/path/c","absolute/path/d"], }; } return{ paths:["absolute/path/a","absolute/path/b"], }; }, }, }, ], }, ], }, }; additionalData Type: typeadditionalData= |string |((content:string,loaderContext:LoaderContext)=>string); Default:undefined Prepends/AppendsLesscodetotheactualentryfile. Inthiscase,theless-loaderwillnotoverridethesourcebutjustprependtheentry'scontent. ThisisespeciallyusefulwhensomeofyourLessvariablesdependontheenvironment: Sinceyou'reinjectingcode,thiswillbreakthesourcemappingsinyourentryfile.Oftenthere'sasimplersolutionthanthis,likemultipleLessentryfiles. string module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ additionalData:`@env:${process.env.NODE_ENV};`, }, }, ], }, ], }, }; function Sync module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ additionalData:(content,loaderContext)=>{ //Moreinformationaboutavailablepropertieshttps://webpack.js.org/api/loaders/ const{resourcePath,rootContext}=loaderContext; constrelativePath=path.relative(rootContext,resourcePath); if(relativePath==="styles/foo.less"){ return"@value:100px;"+content; } return"@value:200px;"+content; }, }, }, ], }, ], }, }; Async module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ additionalData:async(content,loaderContext)=>{ //Moreinformationaboutavailablepropertieshttps://webpack.js.org/api/loaders/ const{resourcePath,rootContext}=loaderContext; constrelativePath=path.relative(rootContext,resourcePath); if(relativePath==="styles/foo.less"){ return"@value:100px;"+content; } return"@value:200px;"+content; }, }, }, ], }, ], }, }; sourceMap Type: typesourceMap=boolean; Default:dependsonthecompiler.devtoolvalue Bydefaultgenerationofsourcemapsdependsonthedevtooloption.Allvaluesenablesourcemapgenerationexceptevalandfalsevalue. webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", { loader:"css-loader", options:{ sourceMap:true, }, }, { loader:"less-loader", options:{ sourceMap:true, }, }, ], }, ], }, }; webpackImporter Type: typewebpackImporter=boolean; Default:true Enables/Disablesthedefaultwebpackimporter. Thiscanimproveperformanceinsomecases.Useitwithcautionbecausealiasesand@importat-rulesstartingwith~willnotwork. webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ webpackImporter:false, }, }, ], }, ], }, }; implementation Type: typeimplementation=object|string; less-loadercompatiblewithLess3and4versions ThespecialimplementationoptiondetermineswhichimplementationofLesstouse.OverridesthelocallyinstalledpeerDependencyversionofless. ThisoptionisonlyreallyusefulfordownstreamtoolingauthorstoeasetheLess3-to-4transition. object webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ implementation:require("less"), }, }, ], }, ], }, }; string webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ implementation:require.resolve("less"), }, }, ], }, ], }, }; Examples Normalusage Chaintheless-loaderwiththecss-loaderandthestyle-loadertoimmediatelyapplyallstylestotheDOM. webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ { loader:"style-loader",//createsstylenodesfromJSstrings }, { loader:"css-loader",//translatesCSSintoCommonJS }, { loader:"less-loader",//compilesLesstoCSS }, ], }, ], }, }; Unfortunately,Lessdoesn'tmapalloptions1-by-1tocamelCase.Whenindoubt,checktheirexecutableandsearchforthedash-caseoption. Sourcemaps ToenablesourcemapsforCSS,you'llneedtopassthesourceMappropertyintheloader'soptions.Ifthisisnotpassed,theloaderwillrespectthesettingforwebpacksourcemaps,setindevtool. webpack.config.js module.exports={ devtool:"source-map",//any"source-map"-likedevtoolispossible module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", { loader:"css-loader", options:{ sourceMap:true, }, }, { loader:"less-loader", options:{ sourceMap:true, }, }, ], }, ], }, }; IfyouwanttoedittheoriginalLessfilesinsideChrome,there'sagoodblogpost.TheblogpostisaboutSassbutitalsoworksforLess. Inproduction Usually,it'srecommendedtoextractthestylesheetsintoadedicatedfileinproductionusingtheMiniCssExtractPlugin.ThiswayyourstylesarenotdependentonJavaScript. Imports Firstwetrytousebuilt-inlessresolvelogic,thenwebpackresolvelogic(aliasesand~). WebpackResolver webpackprovidesanadvancedmechanismtoresolvefiles. less-loaderappliesaLesspluginthatpassesallqueriestothewebpackresolveriflesscouldnotresolve@import. ThusyoucanimportyourLessmodulesfromnode_modules. @import"bootstrap/less/bootstrap"; Using~isdeprecatedandcanberemovedfromyourcode(werecommendit),butwestillsupportitforhistoricalreasons. Whyyoucanremovedit?Theloaderwillfirsttrytoresolve@importasrelative,ifitcannotberesolved,theloaderwilltrytoresolve@importinsidenode_modules. Justprependthemwitha~whichtellswebpacktolookupthemodules. @import"~bootstrap/less/bootstrap"; Defaultresolveroptionscanbemodifiedbyresolve.byDependency: webpack.config.js module.exports={ devtool:"source-map",//any"source-map"-likedevtoolispossible module:{ rules:[ { test:/\.less$/i, use:["style-loader","css-loader","less-loader"], }, ], }, resolve:{ byDependency:{ //Moreoptionscanbefoundherehttps://webpack.js.org/configuration/resolve/ less:{ mainFiles:["custom"], }, }, }, }; It'simportanttoonlyprependitwith~,because~/resolvestothehome-directory.webpackneedstodistinguishbetweenbootstrapand~bootstrap,becauseCSSandLessfileshavenospecialsyntaxforimportingrelativefiles.Writing@import"file"isthesameas@import"./file"; LessResolver Ifyouspecifythepathsoption,moduleswillbesearchedinthegivenpaths.Thisislessdefaultbehavior.pathsshouldbeanarraywithabsolutepaths: webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/i, use:[ { loader:"style-loader", }, { loader:"css-loader", }, { loader:"less-loader", options:{ lessOptions:{ paths:[path.resolve(__dirname,"node_modules")], }, }, }, ], }, ], }, }; Plugins Inordertouseplugins,simplysetthepluginsoptionlikethis: webpack.config.js constCleanCSSPlugin=require('less-plugin-clean-css'); module.exports={ ... { loader:'less-loader', options:{ lessOptions:{ plugins:[ newCleanCSSPlugin({advanced:true}), ], }, }, }, ... }; ℹ️AccesstotheloadercontextinsidethecustomplugincanbedoneusingthepluginManager.webpackLoaderContextproperty. module.exports={ install:function(less,pluginManager,functions){ functions.add("pi",function(){ //Loadercontextisavailablein`pluginManager.webpackLoaderContext` returnMath.PI; }); }, }; Extractingstylesheets BundlingCSSwithwebpackhassomeniceadvantageslikereferencingimagesandfontswithhashedurlsorhotmodulereplacementindevelopment.Inproduction,ontheotherhand,it'snotagoodideatoapplyyourstylesheetsdependingonJSexecution.RenderingmaybedelayedorevenaFOUCmightbevisible.Thusit'softenstillbettertohavethemasseparatefilesinyourfinalproductionbuild. Therearetwopossibilitiestoextractastylesheetfromthebundle: extract-loader(simpler,butspecializedonthecss-loader'soutput) MiniCssExtractPlugin(morecomplex,butworksinalluse-cases) CSSmodulesgotcha ThereisaknownproblemwithLessandCSSmodulesregardingrelativefilepathsinurl(...)statements.Seethisissueforanexplanation. Contributing Pleasetakeamomenttoreadourcontributingguidelinesifyouhaven'tyetdoneso. CONTRIBUTING License MIT Keywordswebpackloaderlesslesscssless.jscsspreprocessorInstallnpmiless-loaderRepositoryGitgithub.com/webpack-contrib/less-loaderHomepagegithub.com/webpack-contrib/less-loaderFundthispackageDownloadsWeeklyDownloads3,110,205Version11.0.0LicenseMITUnpackedSize32.8kBTotalFiles8Lastpublish21daysagoCollaboratorsTryonRunKitReportmalware



請為這篇文章評分?