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
延伸文章資訊
- 1less-loader | webpack 中文网
Use the css-loader or the raw-loader to turn it into a JS module and the ExtractTextPlugin to ext...
- 2less-loader - 一个webpack的Less加载器。将Less编译成CSS ...
入门. 首先,您需要安装 less 和 less-loader : npm install less less-loader --save ...
- 3P11.6-webpack配置less-loader - 华为云社区
这篇再介绍下使用less-loader插件安装配置,通过这篇案例以后我们就可以复制它的步骤,举一反三安装更多的插件。 2.创建less项目. 2.1.创建项目. 创建项目 ...
- 4less-loader - webpack
webpack provides an advanced mechanism to resolve files. The less-loader applies a Less plugin th...
- 5less-loader | webpack 中文文档 - 印记中文
webpack 将Less 编译为CSS 的loader。 快速开始. 首先,你需要先安装 less 和 less-loader : $ npm install less less-loader...