less-loader | webpack 中文网
文章推薦指數: 80 %
Use the css-loader or the raw-loader to turn it into a JS module and the ExtractTextPlugin to extract it into a separate file. 安装. npm install --save-dev less ...
Home对比|webpack中文网品牌指南|webpack中文网概念术语|webpack中文网遵循许可|webpack中文网概念入口起点(entrypoints)|webpack中文网输出(output)|webpack中文网模式(mode)|webpack中文网loader|webpack中文网插件(plugins)|webpack中文网配置(configuration)|webpack中文网模块(modules)|webpack中文网模块解析(moduleresolution)|webpack中文网依赖图(dependencygraph)|webpack中文网manifest|webpack中文网构建目标(targets)|webpack中文网模块热替换(hotmodulereplacement)|webpack中文网配置使用不同语言进行配置(configurationlanguages)|webpack中文网多种配置类型(configurationtypes)|webpack中文网入口和上下文(entryandcontext)|webpack中文网输出(output)|webpack中文网模块(module)|webpack中文网解析(resolve)|webpack中文网插件(plugins)|webpack中文网开发中Server(devServer)|webpack中文网devtool|webpack中文网构建目标(targets)|webpack中文网watch和watchOptions|webpack中文网外部扩展(externals)|webpack中文网性能(performance)|webpack中文网Node|webpack中文网统计信息(stats)|webpack中文网其它选项(otheroptions)|webpack中文网API命令行接口(commandlineinterface)|webpack中文网包含统计数据的文件(statsdata)|webpack中文网Node.jsAPI|webpack中文网模块热替换(hotmodulereplacement)|webpack中文网loaderAPI|webpack中文网模块方法(modulemethods)|webpack中文网模块变量(modulevariables)|webpack中文网PluginAPI|webpack中文网compiler钩子|webpack中文网compilation钩子|webpack中文网resolver|webpack中文网parser|webpack中文网指南安装|webpack中文网起步|webpack中文网管理资源|webpack中文网管理输出|webpack中文网开发|webpack中文网模块热替换|webpack中文网treeshaking|webpack中文网生产环境构建|webpack中文网代码分离|webpack中文网懒加载|webpack中文网缓存|webpack中文网创建library|webpack中文网shimming|webpack中文网渐进式网络应用程序|webpack中文网TypeScript|webpack中文网迁移到新版本|webpack中文网使用环境变量|webpack中文网构建性能|webpack中文网内容安全策略|webpack中文网开发-Vagrant|webpack中文网管理依赖|webpack中文网公共路径(publicpath)|webpack中文网集成(integrations)|webpack中文网插件AggressiveSplittingPlugin|webpack中文网ZopfliWebpackPlugin|webpack中文网BannerPlugin|webpack中文网ClosureWebpackPlugin|webpack中文网CommonsChunkPlugin|webpack中文网ComponentWebpackPlugin|webpack中文网CompressionWebpackPlugin|webpack中文网ContextReplacementPlugin|webpack中文网CopyWebpackPlugin|webpack中文网DefinePlugin|webpack中文网DllPlugin|webpack中文网EnvironmentPlugin|webpack中文网EvalSourceMapDevToolPlugin|webpack中文网ExtractTextWebpackPlugin|webpack中文网HashedModuleIdsPlugin|webpack中文网模块热替换插件(HotModuleReplacementPlugin)|webpack中文网HtmlWebpackPlugin|webpack中文网BabelMinifyWebpackPlugin|webpack中文网IgnorePlugin|webpack中文网LimitChunkCountPlugin|webpack中文网LoaderOptionsPlugin|webpack中文网MinChunkSizePlugin|webpack中文网ModuleConcatenationPlugin|webpack中文网NamedModulesPlugin|webpack中文网NoEmitOnErrorsPlugin|webpack中文网NormalModuleReplacementPlugin|webpack中文网NpmInstallWebpackPlugin|webpack中文网PrefetchPlugin|webpack中文网ProfilingPlugin|webpack中文网ProvidePlugin|webpack中文网SourceMapDevToolPlugin|webpack中文网SplitChunksPlugin|webpack中文网UglifyjsWebpackPlugin|webpack中文网WatchIgnorePlugin|webpack中文网I18nWebpackPlugin|webpack中文网loadersbabel-loader|webpack中文网yaml-frontmatter-loader|webpack中文网cache-loader|webpack中文网coffee-loader|webpack中文网coffee-redux-loader|webpack中文网coverjs-loader|webpack中文网css-loader|webpack中文网exports-loader|webpack中文网expose-loader|webpack中文网extract-loader|webpack中文网file-loader|webpack中文网gzip-loader|webpack中文网html-loader|webpack中文网i18n-loader|webpack中文网imports-loader|webpack中文网istanbul-instrumenter-loader|webpack中文网jshint-loader|webpack中文网json-loader|webpack中文网json5-loader|webpack中文网less-loader|webpack中文网bundle-loader|webpack中文网multi-loader|webpack中文网node-loader|webpack中文网null-loader|webpack中文网polymer-webpack-loader|webpack中文网postcss-loader|webpack中文网raw-loader|webpack中文网react-proxy-loader|webpack中文网restyle-loader|webpack中文网sass-loader|webpack中文网script-loader|webpack中文网source-map-loader|webpack中文网style-loader|webpack中文网svg-inline-loader|webpack中文网thread-loader|webpack中文网transform-loader|webpack中文网url-loader|webpack中文网val-loader|webpack中文网worker-loader|webpack中文网mocha-loader|webpack中文网贡献参与中文文档翻译的全体成员|webpack中文网作者指引|webpack中文网编写一个loader|webpack中文网编写一个插件|webpack中文网插件模式|webpack中文网发布流程|webpack中文网调试|webpack中文网voteorganizationstarter-kitsloaders文件JSON转换编译(Transpiling)模板(Templating)样式清理和测试(Linting&&Testing)框架(Frameworks)babel-loader中文文档安装用法疑难解答babel-loader很慢!babel在每个文件都插入了辅助代码,使代码体积过大!**注意:**transform-runtime和自定义polyfills(比如Promiselibrary)babel的nodeAPI已经被移到babel-core中。
Licenseyaml-frontmatter-loader安装用法cache-loader安装用法Options示例维护人员coffee-loader安装用法OptionsLiterateSourcemapsTranspileMaintainercoffee-redux-loader安装用法Maintainerscoverjs-loader用法Licensecss-loader安装用法选项rooturlaliasimportmodulesScopeComposingImportingminimizesourceMapcamelCaseimportLoaders示例资源提取维护人员exports-loader安装用法维护人员expose-loader安装用法维护人员extract-loaderextract-loaderInstallationExamplesExtractingtheindex.htmlOptionsContributingLicenseSponsorsfile-loader安装用法选项{String}{Function}placeholdershashescontextpublicPathoutputPathuseRelativePathemitFile示例维护人员gzip-loader安装用法维护人员html-loader安装用法示例插值导出格式高级选项导出到HTML文件维护人员i18n-loader用法./colors.json./de-de.colors.json调用配置可选的调用方法Licenseimports-loader安装用法多个值webpack.config.js典型的使用场景jQuery插件自定义的Angular模块禁用AMD维护人员istanbul-instrumenter-loader安装用法结构使用BabelOptionsMaintainersjshint-loader安装用法自定义报告函数维护人员json-loader安装用法通过配置(推荐)维护人员json5-loader安装用法require语句使用loader前缀的用法维护人员LICENSEless-loader安装示例UsageImportswebpackresolverNon-LessimportsLessresolver插件ExtractingstylesheetsSourcemapsCSSmodulesgotcha维护人员bundle-loader安装用法选项(options)name示例维护人员multi-loader安装用法维护人员node-loader安装用法通过命令行(CLI)内联使用维护人员null-loader安装示例维护人员polymer-webpack-loaderPathTranslationsConfiguringtheLoaderinclude:Condition(s)exclude:Condition(s)OptionsignoreLinks:Condition(s)ignorePathReWrite:Condition(s)processStyleLinksBooleanhtmlLoader:ObjectUsewithBabel(orotherJStranspilers)UseofHtmlWebpackPluginShimmingBoostrappingYourApplicationMaintainerspostcss-loaderInstallUsageConfigCascadeOptionsExecConfigPathContext(ctx)PluginsSyntaxesParserSyntaxStringifierSourceMap'inline'ExamplesStylelintCSSModulesCSS-in-JS[ExtractCSS][ExtractPlugin]Maintainersraw-loader安装用法通过命令行(CLI)内联使用维护者react-proxy-loader安装用法配置维护人员restyle-loader安装用法示例维护人员sass-loader安装示例使用导入(Import)url(...)的问题提取样式表Sourcemaps环境变量维护人员Licensescript-loader安装用法内联维护人员source-map-loader安装用法维护人员style-loader安装用法Url可选的(Useable)引用计数器API(ReferenceCounterAPI)选项hmrbaseattrsUrltransformConditionalinsertAtinsertIntosingletonsourceMapconvertToAbsoluteUrls维护人员svg-inline-loader安装配置Query选项removingTags:[...string]warnTags:[...string]removeSVGTagAttrs:booleanremovingTagAttrs:[...string]warnTagAttrs:[...string]classPrefix:boolean||stringidPrefix:boolean||string使用示例维护人员thread-loader安装用法示例维护人员transform-loader安装用法webpack2配置示例webpack1配置示例典型brfs示例维护人员url-loader安装用法Optionsmimetypefallback维护人员val-loader安装用法FunctionInterface{Object}{Promise}ObjectInterfaceOptionsExamplesComplete维护人员worker-loader安装用法ConfigOptionsnameinlinefallbackpublicPathExamplesIntegratingwithES2015ModulesIntegratingwithTypeScriptCross-OriginPolicyMaintainersmocha-loader安装用法命令行接口(CLI)Require选项维护人员less-loader查看原文|查看仓库|编辑此页CompilesLesstoCSS.
Usethecss-loaderortheraw-loadertoturnitintoaJSmoduleandtheExtractTextPlugintoextractitintoaseparatefile.
npminstall--save-devless-loaderless
Theless-loaderrequireslessaspeerDependency.Thusyouareabletocontroltheversionsaccurately.
将css-loader、style-loader和less-loader链式调用,可以把所有样式立即应用于DOM。
//webpack.config.js
module.exports={
...
module:{
rules:[{
test:/\.less$/,
use:[{
loader:"style-loader"//createsstylenodesfromJSstrings
},{
loader:"css-loader"//translatesCSSintoCommonJS
},{
loader:"less-loader"//compilesLesstoCSS
}]
}]
}
};
YoucanpassanyLessspecificoptionstotheless-loadervialoaderoptions.SeetheLessdocumentationforallavailableoptionsindash-case.Sincewe'repassingtheseoptionstoLessprogrammatically,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,checktheirexecutableandsearchforthedash-caseoption.
##
Usually,it'srecommendedtoextractthestylesheetsintoadedicatedfileinproductionusingtheExtractTextPlugin.ThiswayyourstylesarenotdependentonJavaScript:
constExtractTextPlugin=require("extract-text-webpack-plugin");
constextractLess=newExtractTextPlugin({
filename:"[name].[contenthash].css",
disable:process.env.NODE_ENV==="development"
});
module.exports={
...
module:{
rules:[{
test:/\.less$/,
use:extractLess.extract({
use:[{
loader:"css-loader"
},{
loader:"less-loader"
}],
//usestyle-loaderindevelopment
fallback:"style-loader"
})
}]
},
plugins:[
extractLess
]
};
Startingwithless-loader4,youcannowchoosebetweenLess'builtinresolverandwebpack'sresolver.Bydefault,webpack'sresolverisused.
webpack提供了一种解析文件的高级机制。
less-loader应用一个Less插件,并且将所有查询参数传递给webpackresolver。
所以,你可以从node_modules导入你的less模块。
只要加一个~前缀,告诉webpack去查询模块。
@import"~bootstrap/less/bootstrap";
重要的是只使用~前缀,因为~/会解析为主目录。
webpack需要区分bootstrap和〜bootstrap,因为CSS和Less文件没有用于导入相对文件的特殊语法。
@import"file"与@import"./file";写法相同
使用webpackresolver,你可以引入任何文件类型。
你只需要一个导出有效的Less代码的loader。
通常,你还需要设置issuer条件,以确保此规则仅适用于Less文件的导入:
//webpack.config.js
module.exports={
...
module:{
rules:[{
test:/\.js$/,
issuer:/\.less$/,
use:[{
loader:"js-to-less-loader"
}]
}]
}
};
Ifyouspecifythepathsoption,theless-loaderwillnotusewebpack'sresolver.Modules,thatcan'tberesolvedinthelocalfolder,willbesearchedinthegivenpaths.ThisisLess'defaultbehavior.pathsshouldbeanarraywithabsolutepaths:
//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-Lessfilesoraliasingwon'tworkofcourse.
为了使用插件,只需像下面这样简单设置plugins选项:
//webpack.config.js
constCleanCSSPlugin=require("less-plugin-clean-css");
module.exports={
...
{
loader:"less-loader",options:{
plugins:[
newCleanCSSPlugin({advanced:true})
]
}
}]
...
};
BundlingCSSwithwebpackhassomeniceadvantageslikereferencingimagesandfontswithhashedurlsorhotmodulereplacementindevelopment.Inproduction,ontheotherhand,it'snotagoodideatoapplyyourstylesheetsdependingonJSexecution.RenderingmaybedelayedorevenaFOUCmightbevisible.Thusit'softenstillbettertohavethemasseparatefilesinyourfinalproductionbuild.
Therearetwopossibilitiestoextractastylesheetfromthebundle:
extract-loader(simpler,butspecializedonthecss-loader'soutput)
extract-text-webpack-plugin(morecomplex,butworksinalluse-cases)
要启用CSS的sourcemap,你需要将sourceMap选项传递给less-loader和css-loader。
所以你的`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.
如果你要编辑Chrome中的原始Less文件,这里有一个很好的博客文章。
此博客文章是关于Sass的,但它也适用于Less。
ThereisaknownproblemwithLessandCSSmodulesregardingrelativefilepathsinurl(...)statements.Seethisissueforanexplanation.
JohannesEwald
延伸文章資訊
- 1using less-loader in webpack - Stack Overflow
Webpack does not resolve less loader - Stack Overflow
- 2P11.6-webpack配置less-loader - 华为云社区
这篇再介绍下使用less-loader插件安装配置,通过这篇案例以后我们就可以复制它的步骤,举一反三安装更多的插件。 2.创建less项目. 2.1.创建项目. 创建项目 ...
- 3less-loader | webpack 中文文档 - 印记中文
webpack 将Less 编译为CSS 的loader。 快速开始. 首先,你需要先安装 less 和 less-loader : $ npm install less less-loader...
- 4less-loader - webpack
webpack provides an advanced mechanism to resolve files. The less-loader applies a Less plugin th...
- 5less-loader | webpack - JS.ORG
Disclaimer: less-loader is a third-party package maintained by community members, it potentially ...