less-loader | webpack - JS.ORG

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

Disclaimer: less-loader is a third-party package maintained by community members, it potentially does not have the same support, security policy or license as ... ag-gridisproudtopartnerwithwebpackWebpack5Webpack4PrintSectionLoadersFilesJSONTranspilingTemplatingStylingFrameworksAwesomebabel-loaderInstallUsageOptionsTroubleshootingbabel-loaderisslow!Babelisinjectinghelpersintoeachfileandbloatingmycode!TheNode.jsAPIforbabelhasbeenmovedtobabel-core.ExcludelibrariesthatshouldnotbetranspiledCustomizeconfigbasedonwebpacktargetCustomizedLoaderExamplecustomOptions(options:Object):{custom:Object,loader:Object}config(cfg:PartialConfig):Objectresult(result:Result):ResultLicensecoffee-loaderGettingStartedOptionsExamplesCoffeeScriptandBabelLiterateCoffeeScriptContributingLicenseexports-loaderGettingStartedInlineUsingConfigurationOptionstypeexportsContributingLicenseexpose-loaderGettingStartedInlineUsingConfigurationOptionsexposesContributingLicensehtml-loaderGettingStartedOptionssourcespreprocessorminimizeesModuleExamplesDisableurlresolvingusingthe``commentrootsCDNProcessscriptandlinktagsTemplatingPostHTMLExportintoHTMLfilesContributingLicenseimports-loaderGettingStartedInlineUsingConfigurationOptionstypeimportswrapperadditionalCodeContributingLicensenode-loaderGettingStartedInlineConfigurationOptionsflagsnameContributingLicenseremark-loaderUsageOptionsremarkOptionsremoveFrontMatterInspirationExamplesMarkdowntoHTMLMarkdowntoMarkdownContributingLicensesource-map-loaderGettingStartedOptionsfilterSourceMappingUrlExamplesIgnoringWarningsContributingLicensethread-loaderGettingStartedExamplesContributingLicenseval-loaderGettingStartedOptionsexecutableFileReturnObjectPropertiescodesourceMapastdependenciescontextDependenciesbuildDependenciescacheableExamplesSimpleModernizrFigletContributingLicenseCSScss-loaderGettingStartedOptionsurlimportmodulesimportLoaderssourceMapesModuleexportTypeExamplesRecommendDisableurlresolvingusingthe/*webpackIgnore:true*/commentAssetsExtractPureCSS,CSSmodulesandPostCSSResolveunresolvedURLsusinganaliasNamedexportwithcustomexportnamesSeparatingInteroperableCSS-onlyandCSSModulefeaturesContributingLicenseless-loaderGettingStartedOptionslessOptionsadditionalDatasourceMapwebpackImporterimplementationExamplesNormalusageSourcemapsInproductionImportsPluginsExtractingstylesheetsCSSmodulesgotchaContributingLicensepostcss-loaderGettingStartedOptionsexecutepostcssOptionssourceMapimplementationExamplesSugarSSAutoprefixerPostCSSPresetEnvCSSModulesExtractCSSEmitassetsAdddependencies,contextDependencies,buildDependencies,missingDependenciesContributingLicensesass-loaderGettingStartedResolvingimportat-rulesProblemswithurl(...)OptionsimplementationsassOptionssourceMapadditionalDatawebpackImporterwarnRuleAsWarningapiExamplesExtractsCSSintoseparatefilesSourcemapsContributingLicensestyle-loaderGettingStartedOptionsinjectTypeattributesinsertstyleTagTransformbaseesModuleExamplesRecommendNamedexportforCSSModulesSourcemapsNonceContributingLicensestylus-loaderGettingStartedOptionsstylusOptionssourceMapwebpackImporteradditionalDataimplementationExamplesNormalusageSourcemapsUsingnibwithstylusImportJSONfilesInproductionwebpackresolverStylusresolverExtractingstylesheetsContributingLicenseless-loaderDisclaimer:less-loaderisathird-partypackagemaintainedbycommunitymembers,itpotentiallydoesnothavethesamesupport,securitypolicyorlicenseaswebpack,anditisnotmaintainedbywebpack. ALessloaderforwebpack.CompilesLesstoCSS.GettingStartedTobegin,you'llneedtoinstalllessandless-loader:npminstalllessless-loader--save-dev oryarnadd-Dlessless-loader orpnpmadd-Dlessless-loader Thenaddtheloadertoyourwebpackconfig.Forexample:webpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ //compilesLesstoCSS "style-loader", "css-loader", "less-loader", ], }, ], }, };Andrunwebpackviayourpreferredmethod.OptionslessOptionsadditionalDatasourceMapwebpackImporterimplementationlessOptionsType:typelessOptions=import('less').options|((loaderContext:LoaderContext)=>import('less').options})Default:{relativeUrls:true}YoucanpassanyLessspecificoptionstotheless-loaderthroughthelessOptionspropertyintheloaderoptions.SeetheLessdocumentationforallavailableoptionsindash-case.Sincewe'repassingtheseoptionstoLessprogrammatically,youneedtopassthemincamelCasehere:objectUseanobjecttopassoptionsthroughtoLess.webpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ { loader:"style-loader", }, { loader:"css-loader", }, { loader:"less-loader", options:{ lessOptions:{ strictMath:true, }, }, }, ], }, ], }, };functionAllowssettingtheoptionspassedthroughtoLessbasedoffoftheloadercontext.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"], }; }, }, }, ], }, ], }, };additionalDataType:typeadditionalData= |string |((content:string,loaderContext:LoaderContext)=>string);Default:undefinedPrepends/AppendsLesscodetotheactualentryfile. Inthiscase,theless-loaderwillnotoverridethesourcebutjustprependtheentry'scontent.ThisisespeciallyusefulwhensomeofyourLessvariablesdependontheenvironment:Sinceyou'reinjectingcode,thiswillbreakthesourcemappingsinyourentryfile.Oftenthere'sasimplersolutionthanthis,likemultipleLessentryfiles.stringmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ additionalData:`@env:${process.env.NODE_ENV};`, }, }, ], }, ], }, };functionSyncmodule.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; }, }, }, ], }, ], }, };Asyncmodule.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; }, }, }, ], }, ], }, };sourceMapType:typesourceMap=boolean;Default:dependsonthecompiler.devtoolvalueBydefaultgenerationofsourcemapsdependsonthedevtooloption.Allvaluesenablesourcemapgenerationexceptevalandfalsevalue.webpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", { loader:"css-loader", options:{ sourceMap:true, }, }, { loader:"less-loader", options:{ sourceMap:true, }, }, ], }, ], }, };webpackImporterType:typewebpackImporter=boolean;Default:trueEnables/Disablesthedefaultwebpackimporter.Thiscanimproveperformanceinsomecases.Useitwithcautionbecausealiasesand@importat-rulesstartingwith~willnotwork.webpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ webpackImporter:false, }, }, ], }, ], }, };implementationType:typeimplementation=object|string;less-loadercompatiblewithLess3and4versionsThespecialimplementationoptiondetermineswhichimplementationofLesstouse.OverridesthelocallyinstalledpeerDependencyversionofless.ThisoptionisonlyreallyusefulfordownstreamtoolingauthorstoeasetheLess3-to-4transition.objectwebpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ implementation:require("less"), }, }, ], }, ], }, };stringwebpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ "style-loader", "css-loader", { loader:"less-loader", options:{ implementation:require.resolve("less"), }, }, ], }, ], }, };ExamplesNormalusageChaintheless-loaderwiththecss-loaderandthestyle-loadertoimmediatelyapplyallstylestotheDOM.webpack.config.jsmodule.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.SourcemapsToenablesourcemapsforCSS,you'llneedtopassthesourceMappropertyintheloader'soptions.Ifthisisnotpassed,theloaderwillrespectthesettingforwebpacksourcemaps,setindevtool.webpack.config.jsmodule.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.InproductionUsually,it'srecommendedtoextractthestylesheetsintoadedicatedfileinproductionusingtheMiniCssExtractPlugin.ThiswayyourstylesarenotdependentonJavaScript.ImportsFirstwetrytousebuilt-inlessresolvelogic,thenwebpackresolvelogic(aliasesand~).WebpackResolverwebpackprovidesanadvancedmechanismtoresolvefiles. 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.jsmodule.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";LessResolverIfyouspecifythepathsoption,moduleswillbesearchedinthegivenpaths.Thisislessdefaultbehavior.pathsshouldbeanarraywithabsolutepaths:webpack.config.jsmodule.exports={ module:{ rules:[ { test:/\.less$/i, use:[ { loader:"style-loader", }, { loader:"css-loader", }, { loader:"less-loader", options:{ lessOptions:{ paths:[path.resolve(__dirname,"node_modules")], }, }, }, ], }, ], }, };PluginsInordertouseplugins,simplysetthepluginsoptionlikethis:webpack.config.jsconstCleanCSSPlugin=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; }); }, };ExtractingstylesheetsBundlingCSSwithwebpackhassomeniceadvantageslikereferencingimagesandfontswithhashedurlsorhotmodulereplacementindevelopment.Inproduction,ontheotherhand,it'snotagoodideatoapplyyourstylesheetsdependingonJSexecution.RenderingmaybedelayedorevenaFOUCmightbevisible.Thusit'softenstillbettertohavethemasseparatefilesinyourfinalproductionbuild.Therearetwopossibilitiestoextractastylesheetfromthebundle:extract-loader(simpler,butspecializedonthecss-loader'soutput)MiniCssExtractPlugin(morecomplex,butworksinalluse-cases)CSSmodulesgotchaThereisaknownproblemwithLessandCSSmodulesregardingrelativefilepathsinurl(...)statements.Seethisissueforanexplanation.ContributingPleasetakeamomenttoreadourcontributingguidelinesifyouhaven'tyetdoneso.CONTRIBUTINGLicenseMITEditthispage·Printthispage·Jumptorepository«Previouscss-loaderNext»postcss-loader



請為這篇文章評分?