less-loader - webpack
文章推薦指數: 80 %
webpack provides an advanced mechanism to resolve files. The less-loader applies a Less plugin that passes all queries to the webpack resolver. Thus you can ... ag-gridisproudtopartnerwithwebpackFilesJSONTranspilingTemplatingStylingLinting&&TestingFrameworksInstallUsageTroubleshootingbabel-loaderisslow!Babelisinjectinghelpersintoeachfileandbloatingmycode!**NOTE**:transform-runtime&custompolyfills(e.g.Promiselibrary)TheNode.jsAPIforbabelhasbeenmovedtobabel-core.CustomizedLoaderExamplecustomOptions(options:Object):{custom:Object,loader:Object}config(cfg:PartialConfig):Objectresult(result:Result):ResultLicenseRequirementsGettingStartedLicenseMITGettingStartedOptionsExamplesBasicDatabaseIntegrationContributingLicenseInstallUsageOptionsLiterateSourcemapsTranspileMaintainerInstallUsageMaintainersRequirementsGettingStartedExtendingConfigurationFilesGotchasFunction-ConfigParametersExtendingConfigurationFilesinSymlinkedModulesSupportedCompilersAPIloader([options])configconfigPathOptionsallowMissingconfigPathcwdrequireschemaContributingCONTRIBUTINGLicenseMITUsageLicenseGettingStartedtoStringOptionsurlBooleanFunctionimportBooleanFunctionmodulesFeaturesScopeComposingImportingValuesBooleanStringObjectmodelocalIdentNamecontexthashPrefixgetLocalIdentlocalIdentRegExpsourceMapimportLoaderslocalsConventiononlyLocalsExamplesAssetsExtractCSSmodulesandpureCSSContributingLicenseInstallUsageOptionscacheeslintPathformatterfixErrorsandWarningemitErroremitWarningfailOnErrorfailOnWarningquietoutputReportGotchasNoEmitOnErrorsPluginDefiningconfigFileorusingeslint-cpath/.eslintrcChangelogLicenseRequirementsGettingStartedContributingCONTRIBUTINGLicenseMITRequirementsGettingStartedExamplesContributingCONTRIBUTINGLicenseMITextract-loaderInstallationExamplesExtractingtheindex.htmlSourceMapsOptionsContributingLicenseSponsorsGettingStartedOptionsnameStringFunctionoutputPathStringFunctionpublicPathStringFunctionpostTransformPublicPathcontextemitFileregExpPlaceholders[ext][name][path][folder][emoji][emoji:][hash][contenthash][:hash::]digestTypehashTypelength[N]ExamplesNamesDynamicpublicpathdependingonenvironmentvariableatruntimeContributingLicenseInstallUsageMaintainersInstallUsageExamplesInterpolationExportformatsAdvancedoptionsExportintoHTMLfilesMaintainersUsage./colors.json./de-de.colors.jsoncallitoptionsalternativecallsLicenseInstallUsageMultiplevalueswebpack.config.jsTypicalUseCasesjQuerypluginsCustomAngularmodulesDisableAMDMaintainersInstallUsageStructurewithBabelOptionsMaintainersRequirementsGettingStartedOptionsemitErrorsfailOnHintreporterCustomReporterContributingCONTRIBUTINGLicenseMITInstallUsageConfiguration(recommended)MaintainerGettingStartedUsagewithpreconfiguredruleUsagewithrequirestatementloaderprefixContributingLicenseInstallUsageOptionsnameExamplesMaintainersInstallUsageRequireConfig(recommended)OptionsExamplesBasicRequirementsGettingStartedLicenseMITRequirementsGettingStartedInlineLicenseMITGettingStartedContributingLicensePathTranslationsConfiguringtheLoaderinclude:Condition(s)exclude:Condition(s)OptionsignoreLinks:Condition(s)ignorePathReWrite:Condition(s)processStyleLinksBooleanhtmlLoader:ObjectUsewithBabel(orotherJStranspilers)UseofHtmlWebpackPluginShimmingBoostrappingYourApplicationMaintainersInstallUsageConfigCascadeOptionsExecConfigPathContext(ctx)PluginsSyntaxesParserSyntaxStringifierSourceMap'inline'ExamplesStylelintAutoprefixingCSSModulesCSS-in-JS[ExtractCSS][ExtractPlugin]MaintainersGettingStartedExamplesInlineContributingLicenseRequirementsGettingStartedLicenseMITInstallUsageExamplesMaintainersGettingStartedResolvingimportat-rulesProblemswithurl(...)OptionsimplementationsassOptionsObjectFunctionprependDataStringFunctionsourceMapwebpackImporterExamplesExtractsCSSintoseparatefilesSourcemapsContributingLicenseInstallUsageInlineOptionssourceMapuseStrictMaintainersInstallUsageMaintainersGettingStartedOptionsinjectTypestyleTagsingletonStyleTaglazyStyleTaglazySingletonStyleTaglinkTagattributesinsertStringFunctionbaseExamplesSourcemapsNonceattributes__webpack_nonce__InsertstylesattopInsertstylesbeforetargetelementContributingLicenseInstallConfigurationQueryOptionsremovingTags:[...string]warnTags:[...string]removeSVGTagAttrs:booleanremovingTagAttrs:[...string]warnTagAttrs:[...string]classPrefix:boolean||stringidPrefix:boolean||stringExampleUsageMaintainersInstallUsageExamplesMaintainersGettingStartedQueryStringOptionsOptionstransformsContributingLicenseGettingStartedOptionsfallbacklimitNumber|StringBooleanmimetypeContributingLicenseGettingStartedReturnObjectPropertiescodesourceMapastdependenciescontextDependenciescacheableExamplesContributingLicenseRequirementsGettingStartedInlinedConfigOptionsfallbackinlinenamepublicPathExamplesIntegratingwithES2015ModulesIntegratingwithTypeScriptCross-OriginPolicyContributingCONTRIBUTINGLicenseMITGettingStartedExamplesInproductionImportswebpackresolverNon-LessimportsLessresolverPluginsExtractingstylesheetsSourcemapsCSSmodulesgotchaContributingLicenseless-loaderJumptoRepository|EditDocument[![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![cover][cover]][cover-url] [![chat][chat]][chat-url] [![size][size]][size-url] ALessloaderforwebpack.CompilesLesstoCSS. Tobegin,you'llneedtoinstallless-loader: $npminstallless-loader--save-dev Thenaddtheloadertoyourwebpackconfig.Forexample: webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/, loader:'less-loader',//compilesLesstoCSS }, ], }, }; Andrunwebpackviayourpreferredmethod. Theless-loaderrequireslessaspeerDependency. Thusyouareabletocontroltheversionsaccurately. Chaintheless-loaderwiththe css-loaderandthe style-loadertoimmediately applyallstylestotheDOM. webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/, use:[ { loader:'style-loader',//createsstylenodesfromJSstrings }, { loader:'css-loader',//translatesCSSintoCommonJS }, { loader:'less-loader',//compilesLesstoCSS }, ], }, ], }, }; YoucanpassanyLessspecificoptionstotheless-loadervialoaderoptions. SeetheLessdocumentation forallavailableoptionsindash-case.Sincewe'repassingtheseoptionsto Lessprogrammatically,youneedtopassthemincamelCasehere: webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/, use:[ { loader:'style-loader', }, { loader:'css-loader', }, { loader:'less-loader', options:{ strictMath:true, noIeCompat:true, }, }, ], }, ], }, }; Unfortunately,Lessdoesn'tmapalloptions1-by-1tocamelCase.Whenindoubt, checktheirexecutable andsearchforthedash-caseoption. Usually,it'srecommendedtoextractthestylesheetsintoadedicatedfilein productionusingthe MiniCssExtractPlugin. ThiswayyourstylesarenotdependentonJavaScript. Startingwithless-loader4,youcannowchoosebetweenLess'builtinresolver andwebpack'sresolver.Bydefault,webpack'sresolverisused. webpackprovidesan advancedmechanismtoresolvefiles. Theless-loaderappliesaLesspluginthatpassesallqueriestothewebpack resolver.ThusyoucanimportyourLessmodulesfromnode_modules.Just prependthemwitha~whichtellswebpacktolookupthe modules. @import'~bootstrap/less/bootstrap'; It'simportanttoonlyprependitwith~,because~/resolvestothe home-directory.webpackneedstodistinguishbetweenbootstrapand ~bootstrap,becauseCSSandLessfileshavenospecialsyntaxforimporting relativefiles.Writing@import"file"isthesameas@import"./file"; Usingwebpack'sresolver,youcanimportanyfiletype.Youjustneedaloader thatexportsvalidLesscode.Often,youwillalsowanttosettheissuer conditiontoensurethatthisruleisonlyappliedonimportsoriginatingfrom Lessfiles: //webpack.config.js module.exports={ module:{ rules:[ { test:/\.js$/, issuer:/\.less$/, use:[ { loader:'js-to-less-loader', }, ], }, ], }, }; Ifyouspecifythepathsoption,theless-loaderwillnotusewebpack's resolver.Modules,thatcan'tberesolvedinthelocalfolder,willbesearched inthegivenpaths.ThisisLess'defaultbehavior.pathsshouldbeanarray withabsolutepaths: webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/, use:[ { loader:'style-loader', }, { loader:'css-loader', }, { loader:'less-loader', options:{ paths:[path.resolve(__dirname,'node_modules')], }, }, ], }, ], }, }; Inthiscase,allwebpackfeatureslikeimportingnon-Lessfilesoraliasing won'tworkofcourse. Inordertouseplugins,simplysetthe pluginsoptionlikethis: //webpack.config.js constCleanCSSPlugin=require('less-plugin-clean-css'); module.exports={ ... { loader:'less-loader',options:{ plugins:[ newCleanCSSPlugin({advanced:true}) ] } }] ... }; BundlingCSSwithwebpackhassomeniceadvantageslikereferencingimagesand fontswithhashedurlsor hotmodulereplacement indevelopment.Inproduction,ontheotherhand,it'snotagoodideatoapply yourstylesheetsdependingonJSexecution.Renderingmaybedelayedorevena FOUCmightbevisible. Thusit'softenstillbettertohavethemasseparatefilesinyourfinal productionbuild. Therearetwopossibilitiestoextractastylesheetfromthebundle: extract-loader(simpler,but specializedonthecss-loader'soutput) MiniCssExtractPlugin (morecomplex,butworksinalluse-cases) ToenableCSSsourcemaps,you'llneedtopassthesourceMapoptiontothe less-loaderandthecss-loader.Yourwebpack.config.jsshouldlook likethis: webpack.config.js module.exports={ module:{ rules:[ { test:/\.less$/, use:[ { loader:'style-loader', }, { loader:'css-loader', options:{ sourceMap:true, }, }, { loader:'less-loader', options:{ sourceMap:true, }, }, ], }, ], }, }; AlsocheckoutthesourceMapsexample. IfyouwanttoedittheoriginalLessfilesinsideChrome, there'sagoodblogpost. TheblogpostisaboutSassbutitalsoworksforLess. ThereisaknownproblemwithLessand CSSmodulesregardingrelative filepathsinurl(...)statements. Seethisissueforanexplanation. Pleasetakeamomenttoreadourcontributingguidelinesifyouhaven'tyetdoneso. CONTRIBUTING MIT
延伸文章資訊
- 1Webpack 之less-loader 详解- SegmentFault 思否
将打包的less文件分离出来在官方文档看到这样一个例子: {代码...} 但是我... ... 安装. npm install --save-dev less-loader less ...
- 2less-loader | webpack - JS.ORG
Disclaimer: less-loader is a third-party package maintained by community members, it potentially ...
- 3P11.6-webpack配置less-loader | IT人
P11.6-webpack配置less-loader 文章目錄P11.6-webpack配置less-loader1.概述2.建立less專案2.1.建立專案2.2.配置專案3.安裝配置less...
- 4less-loader (Loaders) - Webpack 中文开发手册 - 腾讯云
使用css-loader 或raw-loader 将其转换为JS 模块,然后使用ExtractTextPlugin 将其提取到单独的文件中。 安装. npm install --save-dev...
- 5less-loader | webpack 中文网
Use the css-loader or the raw-loader to turn it into a JS module and the ExtractTextPlugin to ext...