less-loader - webpack

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

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



請為這篇文章評分?