less-loader | webpack - JS.ORG
文章推薦指數: 80 %
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
延伸文章資訊
- 1P11.6-webpack配置less-loader - 华为云社区
这篇再介绍下使用less-loader插件安装配置,通过这篇案例以后我们就可以复制它的步骤,举一反三安装更多的插件。 2.创建less项目. 2.1.创建项目. 创建项目 ...
- 2less-loader (Loaders) - Webpack 中文开发手册 - 腾讯云
使用css-loader 或raw-loader 将其转换为JS 模块,然后使用ExtractTextPlugin 将其提取到单独的文件中。 安装. npm install --save-dev...
- 3less-loader | webpack - JS.ORG
Disclaimer: less-loader is a third-party package maintained by community members, it potentially ...
- 4P11.6-webpack配置less-loader | IT人
P11.6-webpack配置less-loader 文章目錄P11.6-webpack配置less-loader1.概述2.建立less專案2.1.建立專案2.2.配置專案3.安裝配置less...
- 5using less-loader in webpack - Stack Overflow
Webpack does not resolve less loader - Stack Overflow