使用命令行将 .less 文件编译成 .css

¥Compile .less files to .css using the command line

注意! 如果你不喜欢命令行,请了解有关 Less 的图形用户界面 的更多信息。

¥Heads up! If the command line isn't your thing, learn more about GUIs for Less.



使用 npm 安装

¥Install with npm

npm install less -g

-g 选项安装全局可用的 lessc 命令。对于特定版本(或标签),你可以在我们的包名称后添加 @VERSION,例如 npm install less@2.7.1 -g

¥The -g option installs the lessc command available globally. For a specific version (or tag) you can add @VERSION after our package name, e.g. npm install less@2.7.1 -g.

安装 Node 开发

¥Installing for Node Development


¥Alternatively, if you don't want to use the compiler globally, you may be after

npm i less --save-dev

这将在你的项目文件夹中安装最新的正式版 lessc,同时将它添加到你项目的 package.json 中的 devDependencies

¥This will install the latest official version of lessc in your project folder, also adding it to the devDependencies in your project's package.json.

lessc 的测试版

¥Beta releases of lessc

随着新功能的开发,lessc 版本将定期发布到 npm,标记为 beta。这些构建不会作为 @latest 官方版本发布,并且通常在版本中有测试版(使用 lessc -v 获取当前版本)。

¥Periodically, as new functionality is being developed, lessc builds will be published to npm, tagged as beta. These builds will not be published as a @latest official release, and will typically have beta in the version (use lessc -v to get current version).

由于补丁版本是非破坏性的,我们将立即发布补丁版本,alpha/beta/候选版本将作为次要或主要版本升级发布(我们从 1.4.0 开始努力遵循 语义版本控制)。

¥Since patch releases are non-breaking we will publish patch releases immediately and alpha/beta/candidate versions will be published as minor or major version upgrades (we endeavour since 1.4.0 to follow semantic versioning).


¥Server-Side and Command Line Usage

此存储库中包含的二进制文件 bin/lessc 在 *nix、OS X 和 Windows 上与 Node.js 一起使用。

¥The binary included in this repository, bin/lessc works with Node.js on *nix, OS X and Windows.

用法:lessc [option option=parameter ...] <source> [destination]

¥Usage: lessc [option option=parameter ...] <source> [destination]


¥Command Line Usage

lessc [option option=parameter ...] <source> [destination]


¥If source is set to `-' (dash or hyphen-minus), input is read from stdin.



将 bootstrap.less 编译为 bootstrap.css

¥Compile bootstrap.less to bootstrap.css

lessc bootstrap.less bootstrap.css

特定于 lessc 的选项

¥Options specific to lessc

对于所有其他选项,请参见 Less 选项

¥For all other options, see Less Options.


lessc -s lessc --沉默

¥lessc -s lessc --silent


¥Stops any warnings from being shown.



lessc -v
lessc --version



lessc --help
lessc -h


¥Prints a help message with available options and exits.


lessc -M
lessc --depends

将 makefile 导入依赖列表输出到 stdout。

¥Outputs a makefile import dependency list to stdout.


¥No Color



lessc --no-color

清理 CSS

¥Clean CSS

在 v2 of less 中,Clean CSS 不再作为直接依赖包含在内。要在 lessc 中使用干净的 css,请使用 清理 CSS 插件

¥In v2 of less, Clean CSS is no longer included as a direct dependency. To use clean css with lessc, use the clean css plugin.


在浏览器中使用 Less.js 是最简单的入门方式,也便于使用 Less 进行开发,但在生产中,当性能和可靠性很重要时,我们建议使用 Node.js 或许多可用的第三方工具之一进行预编译 .

¥Using Less.js in the browser is the easiest way to get started and convenient for developing with Less, but in production, when performance and reliability is important, we recommend pre-compiling using Node.js or one of the many third party tools available.

首先,链接 .less 样式表,并将 rel 属性设置为“stylesheet/less”:

¥To start off, link your .less stylesheets with the rel attribute set to "stylesheet/less":

<link rel="stylesheet/less" type="text/css" href="styles.less" />

接下来,下载 less.js 并将其包含在页面 <head> 元素的 <script></script> 标记中:

¥Next, download less.js and include it in a <script></script> tag in the <head> element of your page:

<script src="less.js" type="text/javascript"></script>


¥Setting Options

你可以通过编程方式设置选项,方法是将它们设置在脚本标记之前的 less 对象上 - 这会影响所有初始链接标签和 less 的编程使用。

¥You can set options either programmatically, by setting them on a less object before the script tag - this then affects all initial link tags and programmatic usage of less.

  less = {
    env: "development",
    async: false,
    fileAsync: false,
    poll: 1000,
    functions: {},
    dumpLineNumbers: "comments",
    relativeUrls: false,
    rootpath: ":/a.com/"
<script src="less.js"></script>


¥The other way is to specify the options on the script tag, e.g.

  less = {
    env: "development"
<script src="less.js" data-env="development"></script>


¥Or for brevity they can be set as attributes on the script and link tags:

<script src="less.js" data-poll="1000" data-relative-urls="false"></script>
<link data-dump-line-numbers="all" data-global-vars='{ "myvar": "#ddffee", "mystr": "\"quoted\"" }' rel="stylesheet/less" type="text/css" href="less/styles.less">


¥Browser Support

Less.js 支持所有现代浏览器(最新版本的 Chrome、Firefox、Safari 和 Edge)。虽然在生产环境中可以在客户端使用 Less,但请注意这样做会对性能产生影响(尽管 Less 的最新版本要快得多)。此外,如果出现 JavaScript 错误,有时会出现外观问题。这是灵活性与速度的权衡。为了静态网站的最快性能,我们建议在服务器端编译 Less。

¥Less.js supports all modern browsers (recent versions of Chrome, Firefox, Safari, and Edge). While it is possible to use Less on the client side in production, please be aware that there are performance implications for doing so (although the latest releases of Less are quite a bit faster). Also, sometimes cosmetic issues can occur if a JavaScript error occurs. This is a trade off of flexibility vs. speed. For the fastest performance possible for a static web site, we recommend compiling Less on the server side.

在生产中减少使用客户端是有原因的,例如,如果你希望允许用户调整会影响主题的变量,并且你希望实时向他们展示它 - 在这种情况下,用户不必担心要等待样式更新才能看到它。

¥There are reasons to use client-side less in production, such as if you want to allow users to tweak variables which will affect the theme and you want to show it to them in real-time - in this instance a user is not worried about waiting for a style to update before seeing it.



  • 确保在脚本之前包含样式表。

    ¥Make sure you include your stylesheets before the script.

  • 当你链接多个 .less 样式表时,每个样式表都是独立编译的。因此,你在样式表中定义的任何变量、混入或命名空间都无法在任何其他样式表中访问。

    ¥When you link more than one .less stylesheet each of them is compiled independently. So any variables, mixins or namespaces you define in a stylesheet are not accessible in any other.

  • 由于浏览器同源策略,加载外部资源需要 启用 CORS

    ¥Due to the same origin policy of browsers, loading external resources requires enabling CORS


¥Watch Mode

要启用监视模式,选项 env 必须设置为 development。然后在包含 less.js 文件之后,调用 less.watch(),如下所示:

¥To enable Watch mode, option env must be set to development. Then AFTER the less.js file is included, call less.watch(), like this:

<script>less = { env: 'development'};</script>
<script src="less.js"></script>

或者,你可以通过将 #!watch 附加到 URL 来临时启用监视模式。

¥Alternatively, you can enable Watch mode temporarily by appending #!watch to the URL.


¥Modify Variables

启用 Less 变量的运行时修改。当使用新值调用时,Less 文件会在不重新加载的情况下重新编译。简单的基本用法:

¥Enables run-time modification of Less variables. When called with new values, the Less file is recompiled without reloading. Simple basic usage:

  '@buttonFace': '#5B83AD',
  '@buttonText': '#D9EEF2'



可以在 CSS 中输出规则,允许工具定位规则的来源。

¥It is possible to output rules in your CSS which allow tools to locate the source of the rule.

如上所述指定选项 dumpLineNumbers 或将 !dumpLineNumbers:mediaquery 添加到 url。

¥Either specify the option dumpLineNumbers as above or add !dumpLineNumbers:mediaquery to the url.

你可以将 mediaquery 选项与 FireLESS 一起使用(它与 SCSS 媒体查询调试格式相同)。另见 FireLess 和 Less v2comment 选项可用于在内联编译的 CSS 代码中显示文件信息和行号。

¥You can use the mediaquery option with FireLESS (it is identical to the SCSS media query debugging format). Also see FireLess and Less v2. The comment option can be used to display file information and line numbers in the inline compiled CSS code.



在加载 less.js 脚本之前在全局 less 对象中设置选项:

¥Set options in a global less object before loading the less.js script:

<!-- set options before less.js script -->
  less = {
    env: "development",
    logLevel: 2,
    async: false,
    fileAsync: false,
    poll: 1000,
    functions: {},
    dumpLineNumbers: "comments",
    relativeUrls: false,
    globalVars: {
      var1: '"quoted value"',
      var2: 'regular value'
    rootpath: ":/a.com/"
<script src="less.js"></script>

浏览器中特定于 Less.js 的选项

¥Options specific to Less.js in the browser

对于所有其他选项,请参见 Less 选项

¥For all other options, see Less Options.



¥Type: Boolean


¥Default: false

是否使用异步选项请求导入文件。查阅 fileAsync

¥Whether to request the import files with the async option or not. See fileAsync.


类型:String 默认:取决于页面 URL

¥Type: String Default: depends on page URL

要运行的环境可以是 developmentproduction

¥Environment to run may be either development or production.

在生产中,你的 css 缓存在本地存储中,信息消息不会输出到控制台。

¥In production, your css is cached in local storage and information messages are not output to the console.

如果文档的 URL 以 file:// 开头或位于你的本地计算机上或具有非标准端口,它将自动设置为 development

¥If the document's URL starts with file:// or is on your local machine or has a non standard port, it will automatically be set to development.



less = { env: 'production' };



¥Type: String


¥Options: html|console|function


¥Default: html


¥Set the method of error reporting when compilation fails.



¥Type: Boolean


¥Default: false


¥Whether to request the import asynchronously when in a page with a file protocol.

函数(已弃用 - 使用 @plugin)

¥functions (Deprecated - use @plugin)


¥Type: object


¥User functions, keyed by name.

less = {
    functions: {
        myfunc: function() {
            return less.Dimension(1);

它可以像本地 Less 函数一样使用,例如

¥and it can be used like a native Less function e.g.

.my-class {
  border-width: unit(myfunc(), px);



¥Type: Number


¥Default: 2

JavaScript 控制台中的日志记录量。注意:如果你在 production 环境中,你将不会获得任何日志记录。

¥The amount of logging in the javascript console. Note: If you are in the production environment you will not get any logging.

2 - Information and errors
1 - Errors
0 - Nothing



¥Type: Integer


¥Default: 1000


¥The amount of time (in milliseconds) between polls while in watch mode.



¥Type: Boolean


¥Default: false

(可选)将 URL 调整为相对的。如果为 false,则 URL 已经相对于条目较少的文件。

¥Optionally adjust URLs to be relative. When false, URLs are already relative to the entry less file.



¥Type: Boolean

默认:true(以前是 v2 之前的 false

¥Default: true (previously false in before v2)

是否使用每个会话文件缓存。这会缓存 less 文件,以便你可以调用 modifyVars 并且它不会再次检索所有 less 文件。如果你使用 watcher 或调用 refresh 并将 reload 设置为 true,则缓存将在运行前被清除。

¥Whether to use the per session file cache. This caches less files so that you can call modifyVars and it will not retrieve all the less files again. If you use the watcher or call refresh with reload set to true, then the cache will be cleared before running.

Less.js 选项


¥Cross-Platform Options


¥Include Paths

lessc --include-path=PATH1;PATH2 { paths: ['PATH1', 'PATH2'] }

如果 @import 规则中的文件在该确切位置不存在,Less 将在传递给此选项的位置查找它。例如,你可以使用它来指定一个库的路径,你希望在 Less 文件中简单且相对地引用该库。

¥If the file in an @import rule does not exist at that exact location, Less will look for it at the location(s) passed to this option. You might use this for instance to specify a path to a library which you want to be referenced simply and relatively in the Less files.



lessc -rp=resources/
lessc --rootpath=resources/
{ rootpath: 'resources/' }

允许你在 css 中为每个生成的导入和 url 添加路径。这不会影响处理的 Less import 语句,只会影响输出 css 中保留的语句。

¥Allows you to add a path to every generated import and url in your css. This does not affect Less import statements that are processed, just ones that are left in the output css.

例如,如果 css 使用的所有图片都在一个名为 resources 的文件夹中,你可以使用此选项将其添加到 URL,然后可以配置该文件夹的名称。

¥For instance, if all the images the css use are in a folder called resources, you can use this option to add this on to the URL's and then have the name of that folder configurable.

重写 URL

¥Rewrite URLs

lessc -ru=off
lessc --rewrite-urls=off
{ rewriteUrls: 'off' }
lessc -ru=all
lessc --rewrite-urls=all
{ rewriteUrls: 'all' }
lessc -ru=local
lessc --rewrite-urls=local
{ rewriteUrls: 'local' }

默认情况下,URL 保持原样 (off),因此如果你在引用图片的子目录中导入文件,则将在 css 中输出完全相同的 URL。此选项允许你重写导入文件中的 URL,以便 URL 始终相对于已传递给 Less 的基本文件。例如。

¥By default URLs are kept as-is (off), so if you import a file in a sub-directory that references an image, exactly the same URL will be output in the css. This option allows you to rewrite URLs in imported files so that the URL is always relative to the base file that has been passed to Less. E.g.

/* main.less */
@import "global/fonts.less";
/* global/fonts.less */
@font-face {
  font-family: 'MyFont';
  src: url('myfont/myfont.woff2') format('woff2');

没有任何设置或使用 rewriteUrls: 'off',编译 main.less 将输出:

¥With nothing set or with rewriteUrls: 'off', compiling main.less will output:

/* main.less */
/* global/fonts.less */
@font-face {
  font-family: 'MyFont';
  src: url('myfont/myfont.woff2') format('woff2');

使用 rewriteUrls: 'all',它将输出:

¥With rewriteUrls: 'all', it will output:

/* main.less */
/* global/fonts.less */
@font-face {
  font-family: 'MyFont';
  src: url('./global/myfont/myfont.woff2') format('woff2');

对于 rewriteUrls: 'local',它只会重写明确相关的 URL(以 . 开头的 URL):

¥With rewriteUrls: 'local', it will only rewrite URLs that are explicitly relative (those starting with a .):

url('./myfont/myfont.woff2') /* becomes */ url('./global/myfont/myfont.woff2')
url('myfont/myfont.woff2') /* stays */ url('myfont/myfont.woff2')

如果你将 Less 与 CSS 模块 结合使用类似 Node.js 的解析语义,这将很有用。

¥This can be useful in case you're combining Less with CSS Modules which use similar resolving semantics like Node.js.

你可能还想考虑使用 data-uri 函数而不是这个选项,它将图片嵌入到 css 中。

¥You may also want to consider using the data-uri function instead of this option, which will embed images into the css.



发布于 v3.7.0

¥Released v3.7.0

lessc -m=[option]
lessc --math=[option]
{ math: '[option]' }

Less 重新构建了数学选项,以提供介于之前的 strictMath 设置(一直需要括号)和默认设置(在所有情况下都执行数学运算)之间的中间特性。

¥Less has re-built math options to offer an in-between feature between the previous strictMath setting, which required parentheses all the time, and the default, which performed math in all situations.

为了减少与现在自由地在值之间使用 / 符号的 CSS 的冲突,现在有一种数学模式只需要括号进行除法。(现在这是 Less 4 中的默认设置。)"严格的数学" 也进行了调整以更直观地操作,尽管支持旧版行为。

¥In order to cause fewer conflicts with CSS, which now liberally uses the / symbol between values, there is now a math mode that only requires parentheses for division. (This is now the default in Less 4.) "Strict math" has also been tweaked to operate more intuitively, although the legacy behavior is supported.

math 可用的四个选项是:

¥The four options available for math are:

  • always(3.x 默认) - 不太热衷于数学

    ¥always (3.x default) - Less does math eagerly

  • parens-division(默认 4.0) - 使用 / 运算符在括号外不执行除法(但可以使用 ./ 运算符在括号外执行 "forced" - 不推荐使用 ./

    ¥parens-division (4.0 default) - No division is performed outside of parens using / operator (but can be "forced" outside of parens with ./ operator - ./ is deprecated)

  • parens | strict - 所有数学表达式都需要括号。

    ¥parens | strict - Parens required for all math expressions.

  • strict-legacy(4.0 中删除) - 在某些情况下,如果无法计算表达式的任何部分,则不会计算数学值。

    ¥strict-legacy (removed in 4.0) - In some cases, math will not be evaluated if any part of the expression cannot be evaluated.


¥always Example:

.math {
  a: 1 + 1;
  b: 2px / 2;
  c: 2px ./ 2;
  d: (2px / 2);



.math {
  a: 2;
  b: 1px;
  c: 1px;
  d: 1px;




.math {
  a: 1 + 1;
  b: 2px / 2;
  c: 2px ./ 2;
  d: (2px / 2);



.math {
  a: 2;
  b: 2px / 2;
  c: 1px;
  d: 1px;


.math {
  a: 1 + 1;
  b: 2px / 2;
  c: (2px / 2) + (3px / 1);



.math {
  a: 1 + 1;
  b: 2px / 2;
  c: 1px + 3px;


在旧版 strictMath 模式中,括号外的混合表达式意味着不会对整个括号求值。(可能不是你想要的。)

¥In legacy strictMath mode, mixed expressions outside of parentheses means entire parentheses won't evaluate. (Probably not what you want.)

.math {
  a: 1 + 1;
  b: 2px / 2;
  c: (2px / 2) + (3px / 1);



.math {
  a: 1 + 1;
  b: 2px / 2;
  c: (2px / 2) + (3px / 1);


¥Strict Math (Deprecated)

这已被 math 选项取代。

¥This has been replaced by the math option.

相对 URL(已弃用)

¥Relative URLs (deprecated)

lessc -ru
lessc --relative-urls
{ relativeUrls: true }

已被 rewriteUrls: "all" 取代

¥Has been replaced by rewriteUrls: "all"


¥Strict Units

lessc -su=on
lessc --strict-units=on
{ strictUnits: true }


¥Defaults to off/false.

如果没有这个选项,Less 在进行数学运算时会尝试猜测输出单元。例如

¥Without this option, Less attempts to guess at the output unit when it does maths. For instance

.class {
  property: 1px * 2px;

在这种情况下,事情显然不对劲 - 长度乘以长度得出面积,但 css 不支持指定面积。所以我们假设用户希望其中一个值是一个值,而不是长度单位,我们输出 2px

¥In this case, things are clearly not right - a length multiplied by a length gives an area, but css does not support specifying areas. So we assume that the user meant for one of the values to be a value, not a unit of length and we output 2px.


¥With strict units on, we assume this is a bug in the calculation and throw an error.

IE8 兼容性(已弃用)

¥IE8 Compatibility (Deprecated)

lessc --ie-compat { ieCompat: true }

从 v3.0.0 开始默认为 False。目前仅用于 data-uri 功能,以确保不会创建太大而浏览器无法处理的图片。

¥False by default starting in v3.0.0. Currently only used for the data-uri function to ensure that images aren't created that are too large for the browser to handle.

启用内联 JavaScript(已弃用)

¥Enable Inline JavaScript (Deprecated)

lessc --js { javascriptEnabled: true }

从 v3.0.0 开始默认为 False。启用 .less 文件中内联 JavaScript 的评估。这给一些开发者带来了安全问题,他们不希望样式表的用户输入具有可执行代码。

¥False by default starting in v3.0.0. Enables evaluation of JavaScript inline in .less files. This created a security problem for some developers who didn't expect user input for style sheets to have executable code.

替换为 @plugin 选项。

¥Replaced with the @plugin option.


¥Global Variables

lessc --global-var="color1=red" { globalVars: { color1: 'red' } }

该选项定义了一个可以被文件引用的变量。实际上,声明放在基本 Less 文件的顶部,这意味着它可以使用,但如果在文件中定义了这个变量,它也可以被覆盖。

¥This option defines a variable that can be referenced by the file. Effectively the declaration is put at the top of your base Less file, meaning it can be used but it also can be overridden if this variable is defined in the file.


¥Modify Variables

lessc --modify-var="color1=red" { modifyVars: { color1: 'red' } }

与全局变量选项相反,这会将声明放在基础文件的末尾,这意味着它将覆盖 Less 文件中定义的任何内容。

¥As opposed to the global variable option, this puts the declaration at the end of your base file, meaning it will override anything defined in your Less file.


¥URL Arguments

lessc --url-args="cache726357" { urlArgs: 'cache726357' }

此选项允许你指定一个参数以继续访问每个 URL。例如,这可以用于缓存清除。

¥This option allows you to specify a argument to go on to every URL. This may be used for cache-busting for instance.


¥Line Numbers (Deprecated)

lessc --line-numbers=comments
lessc --line-numbers=mediaquery
lessc --line-numbers=all
{ dumpLineNumbers: 'comments' }

生成内联源映射。在浏览器开始支持 sourcemaps 之前,这是唯一的选择。

¥Generates inline source-mapping. This was the only option before browsers started supporting sourcemaps.


¥Pre-Loaded Plugin


¥See: Pre-Loaded Plugins


lessc --lint -l { lint: true }

运行 less 解析器并只报告错误而没有任何输出。

¥Runs the less parser and just reports errors without any output.


¥Compress (Deprecated)

lessc --compress -x { compress: true }

使用较少的内置压缩进行压缩。这做得不错,但没有利用专用 css 压缩的所有技巧。一般来说,我们建议在你的 Less 转换为 CSS 后,使用第三方工具清理和压缩 CSS。

¥Compress using less built-in compression. This does an okay job but does not utilise all the tricks of dedicated css compression. In general, we recommend looking at third-party tools that clean and compress CSS after your Less has been transformed to CSS.

允许从不安全的 HTTPS 主机导入

¥Allow Imports from Insecure HTTPS Hosts

lessc --insecure { insecure: true }


¥Source Map Options

这些选项中的大多数不适用于在浏览器中使用 Less.js,因为你应该使用预编译的 Less 文件生成源映射。

¥Most of these options are not applicable to using Less.js in the browser, as you should generate a source map with your pre-compiled Less files.


¥Generate a Source Map

lessc --source-map { sourceMap: {} }

告诉 less 生成一个 sourcemap。

¥Tells less to generate a sourcemap.


¥Source Map Output Filename

lessc --source-map=file.map { sourceMap: { outputFilename: 'file.map' } }


¥Source Map Rootpath

lessc --source-map-rootpath=dev-files/ { sourceMap: { sourceMapRootpath: 'dev-files/' } }

指定一个根路径,该路径应添加到 sourcemap 中的每个 less 文件路径以及输出 css 中指定的映射文件的路径。

¥Specifies a rootpath that should be prepended to each of the less file paths inside the sourcemap and also to the path to the map file specified in your output css.

因为 basepath 默认是 input less 文件的目录,rootpath 默认是 sourcemap 输出文件到 input less 文件的基目录的路径。

¥Because the basepath defaults to the directory of the input less file, the rootpath defaults to the path from the sourcemap output file to the base directory of the input less file.

例如,如果你在 Web 服务器的根目录中生成了一个 css 文件,但你的源 less/css/map 文件位于不同的文件夹中,请使用此选项。所以对于上面的选项你可能有

¥Use this option if for instance you have a css file generated in the root on your web server but have your source less/css/map files in a different folder. So for the option above you might have



¥Source Map Basepath

lessc --source-map-basepath=less-files/ { sourceMap: { sourceMapBasepath: 'less-files/' } }

这与 rootpath 选项相反,它指定应从输出路径中删除的路径。例如,如果你正在 less-files 目录中编译一个文件,但源文件将在你的 Web 服务器的根目录或当前目录中可用,你可以指定它以删除路径的附加 less-files 部分。

¥This is the opposite of the rootpath option, it specifies a path which should be removed from the output paths. For instance if you are compiling a file in the less-files directory but the source files will be available on your web server in the root or current directory, you can specify this to remove the additional less-files part of the path.


¥It defaults to the path to the input less file.

在源映射中包含 Less 源

¥Include Less Source in the Source Map

lessc --source-map-include-source { sourceMap: { outputSourceFiles: true } }

此选项指定我们应该将所有 Less 文件包含到 sourcemap 中。这意味着你只需要你的映射文件即可到达你的原始来源。

¥This option specifies that we should include all of the Less files in to the sourcemap. This means that you only need your map file to get to your original source.

这可以与 map inline 选项结合使用,因此你根本不需要任何额外的外部文件。

¥This can be used in conjunction with the map inline option so that you do not need to have any additional external files at all.


¥Source Map Map Inline

lessc --source-map-inline { sourceMap: { sourceMapFileInline: true } }

此选项指定映射文件应内嵌在输出 CSS 中。这不推荐用于生产,但对于开发,它允许编译器生成单个输出文件,在支持它的浏览器中,使用已编译的 css,但向你显示未编译的 less 源。

¥This option specifies that the map file should be inline in the output CSS. This is not recommended for production, but for development it allows the compiler to produce a single output file which in browsers that support it, use the compiled css but show you the non-compiled less source.

源映射 URL

¥Source Map URL

lessc --source-map-url=../my-map.json { sourceMap: { sourceMapURL: '../my-map.json' } }

允许你覆盖指向映射文件的 css 中的 URL。这是针对 rootpath 和 basepath 选项没有产生你需要的内容的情况。

¥Allows you to override the URL in the css that points at the map file. This is for cases when the rootpath and basepath options are not producing exactly what you need.


在 Less.js 中开始解析之前加载插件

¥Loading plugins before parsing begins in Less.js

虽然使用插件的最简单方法是使用 @plugin 规则,但在 Node.js 环境中,你可以通过命令行或在 Less 选项 中指定它来预加载全局 Less.js 插件。

¥While the easiest way to use a plugin is using the @plugin at-rule, in a Node.js environment, you can pre-load a global Less.js plugin via the command line or by specifying it in the Less options.



如果你想添加一个 Less.js 预处理器,预加载插件是必要的。也就是说,一个在解析甚至开始之前被调用并传递原始 Less 源的插件。Sass-To-Less 预处理器插件 就是一个例子。

¥Pre-loading plugins is necessary if you want to add a Less.js Pre-processor. That is, a plugin that gets called and passed the raw Less source before parsing even starts. An example of this would be a Sass-To-Less Pre-processor plugin.

注意:预评估插件不需要预加载(在解析 Less 源之后,但在评估之前)。

¥Note: pre-loading is not necessary for pre-evaluation plugins (after Less source is parsed, but before it is evaluated).



¥Using the Command Line

如果你正在使用 lessc,你需要做的第一件事就是安装那个插件。在像 NPM 这样的注册表中,我们建议使用 "少-插件-" 前缀注册 Less.js 插件(以便于搜索),但这不是必需的。因此,对于自定义插件,你可以安装:

¥If you are using lessc, the first thing you need to do is install that plugin. In registries like NPM, we recommend a Less.js plugin is registered with the "less-plugin-" prefix (for easier searching), though that isn't required. So, for a custom plugin, you might install with:

npm install less-plugin-myplugin


¥To use the plugin, you can pass this on the command line by simply writing:

lessc --myplugin

只要存在未知的 Less 选项(如 "myplugin"),Less.js 将尝试加载 "less-plugin-myplugin" 和 "myplugin" 模块作为插件。

¥Less.js will try to load either the "less-plugin-myplugin" and the "myplugin" modules as plugins whenever there's an unknown Less option (like "myplugin").


¥You can also explicitly specify the plugin with:

lessc --plugin=myplugin


¥To pass options to the plugin, you can write that in one of two ways.

lessc --myplugin="advanced"
lessc --plugin=myplugin=advanced

通过 Less.js 加载插件

¥Loading a Plugin via Less.js

在 Node 中,需要插件并将其作为选项插件传递给数组中的 less。例如。

¥In Node, require the plugin and pass it to less in an array as an option plugins. E.g.

var LessPlugin = require('less-plugin-myplugin');
less.render(myCSS, { plugins: [LessPlugin] })
    function(output) { },
    function(error) { }


less 的主要入口点是 less.render 函数。这采用以下格式

¥The main entry point into less is the less.render function. This takes the following format

less.render(lessInput, options)
    .then(function(output) {
        // output.css = string of css
        // output.map = string of sourcemap
        // output.imports = array of string filenames of the imports referenced
    function(error) {

// or...

less.render(css, options, function(error, output) {})

options 参数是可选的。如果你指定回调,则不会返回 promise,如果你没有指定回调,则会给出 promise。在幕后,使用了回调版本,以便可以同步使用 less。

¥The options argument is optional. If you specify a callback then a promise will not be returned, where as if you do not specify a callback a promise will be given. Under the hood, the callback version is used so that less can be used synchronously.

如果你想渲染一个文件,你首先要将它读入一个字符串(传递给 less.render),然后将选项上的文件名字段设置为主文件的文件名。less 将处理所有导入进程。

¥If you wanted to render a file, you would first read it into a string (to pass to less.render) and then set the filename field on options to be the filename of the main file. less will handle all the processing of the imports.

sourceMap 选项是一个对象,它使你能够设置子 sourcemap 选项。可用的子选项是:sourceMapURLsourceMapBasepathsourceMapRootpathoutputSourceFilessourceMapFileInline。请注意,sourceMap 选项现在不适用于浏览器编译器中的 less.js。

¥The sourceMap option is an object which enables you to set sub sourcemap options. Available sub options are: sourceMapURL,sourceMapBasepath,sourceMapRootpath,outputSourceFiles and sourceMapFileInline. Notice that the sourceMap option is not available for the less.js in browser compiler now.

    .then(function(output) {
        // output.css = string of css
        // output.map = undefined
less.render(lessInput, {sourceMap: {}})
    .then(function(output) {
        // output.css = string of css
        // output.map = string of sourcemap
less.render(lessInput, {sourceMap: {sourceMapFileInline: true}})
    .then(function(output) {
        // output.css = string of css \n /*# sourceMappingURL=data:application/json;base64,eyJ2ZXJ..= */
        // output.map = undefined


¥Getting Access to the Log


¥You can add a log listener with the following code

    debug: function(msg) {
    info: function(msg) {
    warn: function(msg) {
    error: function(msg) {

注意:所有功能都是可选的。错误不会被记录,而是被传递回 less.render 中的回调或 promise

¥Note: all functions are optional. An error will not be logged, but instead is passed back to the callback or promise in less.render



¥Coming soon

为 Less.js 做贡献


¥Thanks for thinking about contributing! Please read the contributing instructions carefully to avoid wasted work.


¥Install These Tools

确保路径已设置。如果你启动你最喜欢的命令行并键入 node -v,你应该会看到节点编译器。如果你运行 phantomjs -v,你应该看到 phantomjs 版本号。

¥make sure the paths are setup. If you start your favourite command line and type node -v you should see the node compiler. If you run phantomjs -v you should see the phantomjs version number.

  • 在本地克隆你的 less.js 仓库

    ¥clone your less.js repository locally

  • 导航到本地 less.js 存储库并运行 npm install 这将安装 less 的 npm 依赖。

    ¥navigate to your local less.js repository and run npm install this installs less' npm dependencies.



Grunt 用于运行开发命令,例如测试、构建和基准测试。如果全局安装了 grunt-cli,则可以使用 grunt [command_name] 运行它们,也可以使用 npm run grunt -- [command_name] 运行它们。

¥Grunt is used in order to run development commands such as tests, builds, and benchmarks. You can run them either with grunt [command_name] if you have grunt-cli installed globally or with npm run grunt -- [command_name].

如果你转到 Less 存储库的根目录,你应该能够执行 npm testnpm run grunt -- test 的一个方便的别名) - 这应该运行所有测试。仅针对特定浏览器,运行 npm run grunt -- browsertest 如果你想针对文件试用当前版本的 less,从这里执行 node bin/lessc path/to/file.less

¥If you go to the root of the Less repository you should be able to do npm test (a handy alias for npm run grunt -- test) - this should run all the tests. For the browser specific only, run npm run grunt -- browsertest If you want to try out the current version of less against a file, from here do node bin/lessc path/to/file.less

要调试浏览器测试,请运行 npm run grunt -- browsertest-server,然后转到 http://localhost:8088/tmp/browser/ 查看测试运行程序页面。

¥To debug the browser tests, run npm run grunt -- browsertest-server then go to http://localhost:8088/tmp/browser/ to see the test runner pages.

可选的:要获取 Less 编译器的当前版本,请执行 npm -g install less - npm 是节点包管理器,"-g" 安装它以便全局可用。

¥Optional: To get the current version of the Less compiler do npm -g install less - npm is the node package manager and "-g" installs it to be available globally.

你现在应该可以执行 lessc file.less,如果有合适的 file.less,那么它将被编译并输出到标准输出。然后,你可以将其与本地运行 (node bin/lessc file.less) 进行比较。

¥You should now be able to do lessc file.less and if there is an appropriate file.less then it will be compiled and output to the stdout. You can then compare it to running locally (node bin/lessc file.less).

其他 grunt 命令

¥Other grunt commands

  • npm run grunt -- benchmark - 运行我们的基准测试以获得一些性能数据

    ¥npm run grunt -- benchmark - run our benchmark tests to get some numbers on performance

  • npm run grunt -- stable 创建新版本

    ¥npm run grunt -- stable to create a new release

  • npm run grunt -- readme 在根目录下生成一个新的 readme.md(每次发布后)

    ¥npm run grunt -- readme to generate a new readme.md in the root directory (after each release)

如何在其他环境中运行 Less

¥How to Run Less in Other Environments

如果查看 libs 文件夹,你将看到 lessless-nodeless-browserless 文件夹是纯 javascript,没有环境细节。如果你需要 less/libs/less,你会得到一个函数,它接受一个环境对象和一个文件管理器数组。文件管理器是相同的文件管理器,也可以作为插件编写。

¥If you look in the libs folder you will see less, less-node, less-browser. The less folder is pure javascript with no environment specifics. if you require less/libs/less, you get a function that takes an environment object and an array of file managers. The file managers are the same file managers that can also be written as a plugin.

var createLess = require("less/libs/less"),
    myLess = createLess(environment, [myFileManager]);

环境 api 在 less/libs/less/environment/environment-api.js 中指定,文件管理器 api 在 less/libs/less/environment/file-manager-api.js 中指定。

¥The environment api is specified in less/libs/less/environment/environment-api.js and the file manager api is specified in less/libs/less/environment/file-manager-api.js.

对于文件管理器,我们强烈建议将原型设置为新的 AbstractFileManager - 这允许你覆盖所需的内容,并允许我们在不破坏现有文件管理器的情况下实现新功能。有关文件管理器的示例,请参阅 2 节点实现、浏览器实现或 npm 导入插件实现。

¥For file managers we highly recommend setting the prototype as a new AbstractFileManager - this allows you to override what is needed and allows us to implement new functions without breaking existing file managers. For an example of file managers, see the 2 node implementations, the browser implementation or the npm import plugin implementation.



如果你看一下 http://www.gliffy.com/go/publish/4784259,这是一个关于 less 如何工作的概述图。警告!它需要更新 v2 更改。

¥If you look at http://www.gliffy.com/go/publish/4784259, This is an overview diagram of how less works. Warning! It needs updating with v2 changes.