命令行使用

Edit the markdown source for "command-line-usage"

命令行使用

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

注意!如果你不熟悉命令行,可以了解更多关于 Less 的图形界面工具

安装

使用 npm 安装

npm install less -g

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

为 Node 开发安装

另外,如果你不想全局安装编译器,可以使用

npm i less --save-dev

这将在你的项目文件夹中安装最新的官方版本的 lessc,并将其添加到项目的 package.json 中的 devDependencies

lessc 的测试版本

周期性地,在开发新功能时,lessc 构建版本将发布到 npm,并标记为测试版。这些构建不会作为 @latest 官方版本发布,通常版本号中会包含 beta(使用 lessc -v 获取当前版本)。

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

服务器端和命令行使用

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

用法lessc [选项 选项=参数 ...] <源文件> [目标文件]

命令行使用

lessc [选项 选项=参数 ...] <源文件> [目标文件]

如果源文件设置为 -(破折号或连字符),则从标准输入读取输入。

示例

将 bootstrap.less 编译为 bootstrap.css

lessc bootstrap.less bootstrap.css

lessc 特定选项

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

静默模式

lessc -s lessc --silent

停止显示任何警告。

版本

lessc -v
lessc --version

帮助

lessc --help
lessc -h

打印可用选项的帮助信息并退出。

Makefile

lessc -M
lessc --depends

输出 makefile 导入依赖列表到标准输出。

无颜色

已弃用

lessc --no-color

Clean CSS

在 less 的 v2 版本中,Clean CSS 不再作为直接依赖项。要在 lessc 中使用 clean css,请使用 clean css 插件


浏览器使用

Edit the markdown source for "using-less-in-the-browser"

浏览器使用

在浏览器中使用 Less.js 是开始使用和开发 Less 最简单的方式,但在生产环境中,当性能和可靠性很重要时,我们建议使用 Node.js 或众多第三方工具进行预编译。

首先,将你的 .less 样式表的 rel 属性设置为 "stylesheet/less":

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

接下来,下载 less.js 并在页面的 <head> 元素中的 <script></script> 标签中引入:

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

设置选项

你可以通过两种方式设置选项:

  1. 在脚本标签之前,在 less 对象上以编程方式设置 - 这将影响所有初始链接标签和 less 的编程使用:
<script>
  less = {
    env: "development",
    async: false,
    fileAsync: false,
    poll: 1000,
    functions: {},
    dumpLineNumbers: "comments",
    relativeUrls: false,
    rootpath: ":/a.com/"
  };
</script>
<script src="less.js"></script>
  1. 在脚本标签上指定选项,例如:
<script>
  less = {
    env: "development"
  };
</script>
<script src="less.js" data-env="development"></script>

或者为简洁起见,可以在脚本和链接标签上设置属性:

<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">

浏览器支持

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

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

提示

  • 确保在脚本之前包含你的样式表。
  • 当你链接多个 .less 样式表时,每个样式表都是独立编译的。因此,你在一个样式表中定义的任何变量、混合或命名空间在其他样式表中都是不可访问的。
  • 由于浏览器的同源策略,加载外部资源需要启用 CORS

监视模式

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

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

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

修改变量

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

less.modifyVars({
  '@buttonFace': '#5B83AD',
  '@buttonText': '#D9EEF2'
});

调试

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

可以指定 dumpLineNumbers 选项,或在 URL 中添加 !dumpLineNumbers:mediaquery

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

选项

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

<!-- 在 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>
<script src="less.js"></script>

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

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

async

类型:布尔值

默认值:false

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

env

类型:字符串 默认值:取决于页面 URL

运行环境可以是 developmentproduction

在生产环境中,你的 CSS 将缓存在本地存储中,并且不会在控制台输出信息消息。

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

例如:

less = { env: 'production' };

errorReporting

类型:字符串

选项:html|console|function

默认值:html

设置编译失败时的错误报告方法。

fileAsync

类型:布尔值

默认值:false

在使用文件协议的页面中是否异步请求导入。

functions(已弃用 - 使用 @plugin)

类型:对象

用户函数,以名称为键。

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

可以像原生 Less 函数一样使用,例如:

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

logLevel

类型:数字

默认值:2

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

2 - 信息和错误
1 - 错误
0 - 无

poll

类型:整数

默认值:1000

在监视模式下,轮询之间的时间间隔(以毫秒为单位)。

relativeUrls

类型:布尔值

默认值:false

可选地调整 URL 为相对路径。当为 false 时,URL 已经相对于入口 less 文件。

useFileCache

类型:布尔值

默认值:true(在 v2 之前为 false

是否使用每个会话的文件缓存。这会缓存 less 文件,以便你可以调用 modifyVars 而不需要再次检索所有 less 文件。 如果你使用监视器或调用带有 reload 设置为 true 的 refresh,则缓存将在运行前被清除。


Less.js 选项

Edit the markdown source for "less-options"

跨平台选项

包含路径

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

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

根路径

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

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

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

重写 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 的基本文件。例如:

/* 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 将输出:

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

使用 rewriteUrls: 'all' 将输出:

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

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

url('./myfont/myfont.woff2') /* 变为 */ url('./global/myfont/myfont.woff2')
url('myfont/myfont.woff2') /* 保持不变 */ url('myfont/myfont.woff2')

这在与使用类似 Node.js 解析语义的 CSS 模块 结合时可能很有用。

你可能还想考虑使用 data-uri 函数代替此选项,它会将图像嵌入到 CSS 中。

数学运算

发布于 v3.7.0

lessc -m=[选项]
lessc --math=[选项]
{ math: '[选项]' }

Less 重新构建了数学选项,以在之前需要始终使用括号的 strictMath 设置和默认情况下在所有情况下执行数学运算之间提供一个中间特性。

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

math 可用的四个选项是:

  • always(3.x 默认)- Less 积极地执行数学运算
  • parens-division(4.0 默认) - 不在括号外使用 / 运算符执行除法(但可以在括号外使用 ./ 运算符 - ./ 已弃用)
  • parens | strict - 所有数学表达式都需要括号
  • strict-legacy(在 4.0 中已移除)- 在某些情况下,如果表达式的任何部分无法求值,则不会执行数学运算

always 示例:

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

输出:

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

parens-division

示例:

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

输出:

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

strict

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

输出:

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

strict-legacy

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

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

输出:

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

严格数学(已弃用)

这已被 math 选项替代。

相对 URLs(已弃用)

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

已被 rewriteUrls: "all" 替代

严格单位

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

默认为关闭/假。

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

.class {
  property: 1px * 2px;
}

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

启用严格单位后,我们假设这是计算中的错误,并抛出错误。

IE8 兼容性(已弃用)

lessc --ie-compat { ieCompat: true }

从 v3.0.0 开始默认为 false。目前仅用于 data-uri 函数,以确保不会创建浏览器无法处理的图像。

启用内联 JavaScript(已弃用)

lessc --js { javascriptEnabled: true }

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

已被 @plugin 选项替代。

全局变量

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

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

修改变量

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

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

URL 参数

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

此选项允许你为每个 URL 指定一个参数。例如,这可以用于缓存破坏。

行号(已弃用)

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

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

预加载插件

参见:预加载插件

代码检查

lessc --lint -l { lint: true }

运行 Less 解析器并仅报告错误,不生成任何输出。

压缩(已弃用)

lessc --compress -x { compress: true }

使用 Less 内置压缩。这做得还不错,但没有利用专用 CSS 压缩的所有技巧。通常,我们建议使用第三方工具在 Less 转换为 CSS 后清理和压缩 CSS。

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

lessc --insecure { insecure: true }

Source Map Options

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: {} }

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/' } }

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.

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.

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

output.css
dev-files/output.map
dev-files/main.less

Source Map Basepath

lessc --source-map-basepath=less-files/ { sourceMap: { sourceMapBasepath: '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.

Include Less Source in the Source Map

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

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.

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 } }

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.

Source Map URL

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

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.


预加载插件

Edit the markdown source for "plugins"

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

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

预处理

如果你想添加 Less.js 预处理器,则需要预加载插件。也就是说,在解析开始之前就调用并传递原始 Less 源代码的插件。一个例子是 Sass 转 Less 预处理器插件

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

Node.js

使用命令行

如果你使用 lessc,首先需要安装该插件。在 NPM 等注册表中,我们建议 Less.js 插件注册时带有 "less-plugin-" 前缀(便于搜索),但这不是必需的。因此,对于自定义插件,你可能会这样安装:

npm install less-plugin-myplugin

要使用插件,你可以在命令行上简单地写:

lessc --myplugin

每当出现未知的 Less 选项(如 "myplugin")时,Less.js 都会尝试加载 "less-plugin-myplugin" 和 "myplugin" 模块作为插件。

你也可以明确指定插件:

lessc --plugin=myplugin

要向插件传递选项,你可以用以下两种方式之一编写:

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

通过 Less.js 加载插件

在 Node 中,引入插件并将其作为选项传递给 less。例如:

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

编程式使用

Edit the markdown source for "programmatic-usage"

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

less.render(lessInput, options)
    .then(function(output) {
        // output.css = CSS 字符串
        // output.map = 源映射字符串
        // output.imports = 引用的导入文件名字符串数组
    },
    function(error) {
    });

// 或者...

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

options 参数是可选的。如果你指定了回调函数,则不会返回 Promise;如果你没有指定回调函数,则会返回 Promise。 在底层,使用回调版本是为了让 less 可以同步使用。

如果你想渲染一个文件,你首先需要将其读取为字符串(传递给 less.render),然后在 options 中设置 filename 字段为主文件的文件名。less 将处理所有导入的处理。

sourceMap 选项是一个对象,允许你设置子源映射选项。可用的子选项有:sourceMapURLsourceMapBasepathsourceMapRootpathoutputSourceFilessourceMapFileInline。请注意,sourceMap 选项现在在浏览器编译器中不可用。

less.render(lessInput)
    .then(function(output) {
        // output.css = CSS 字符串
        // output.map = 未定义
}
//,
less.render(lessInput, {sourceMap: {}})
    .then(function(output) {
        // output.css = CSS 字符串
        // output.map = 源映射字符串
}
//或者,
less.render(lessInput, {sourceMap: {sourceMapFileInline: true}})
    .then(function(output) {
        // output.css = CSS 字符串 \n /*# sourceMappingURL=data:application/json;base64,eyJ2ZXJ..= */
        // output.map = 未定义
}

获取日志访问权限

你可以使用以下代码添加日志监听器:

less.logger.addListener({
    debug: function(msg) {
    },
    info: function(msg) {
    },
    warn: function(msg) {
    },
    error: function(msg) {
    }
});

注意:所有函数都是可选的。错误不会被记录,而是在 less.render 的回调或 Promise 中传回。


贡献 Less.js

Edit the markdown source for "developing-less"

感谢您考虑贡献!请仔细阅读 贡献说明,以避免浪费精力。

安装这些工具

确保路径已正确设置。如果您打开您喜欢的命令行并输入 node -v,应该会看到 node 编译器。如果运行 phantomjs -v,应该会看到 phantomjs 的版本号。

  • 在本地克隆您的 less.js 仓库
  • 导航到本地 less.js 仓库并运行 npm install,这将安装 less 的 npm 依赖。

使用方法

使用 Grunt 来运行开发命令,如测试、构建和基准测试。您可以使用 grunt [command_name](如果全局安装了 grunt-cli)或 npm run grunt -- [command_name] 来运行这些命令。

如果您进入 Less 仓库的根目录,应该可以执行 npm testnpm run grunt -- test 的快捷方式)- 这将运行所有测试。对于仅针对浏览器的测试,运行 npm run grunt -- browsertest。如果要尝试对文件使用当前版本的 less,在这里执行 node bin/lessc path/to/file.less

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

可选:要获取 Less 编译器的当前版本,执行 npm -g install less - npm 是 node 包管理器,"-g" 表示全局安装。

现在您应该能够执行 lessc file.less,如果存在相应的 file.less,它将被编译并输出到 stdout。您可以将其与本地运行 (node bin/lessc file.less) 进行比较。

其他 grunt 命令

  • npm run grunt -- benchmark - 运行我们的基准测试以获取性能数据
  • npm run grunt -- stable 创建新版本
  • npm run grunt -- readme 在根目录生成新的 readme.md(每次发布后)

如何在其他环境中运行 Less

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

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 中指定。

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

指南

如果查看 http://www.gliffy.com/go/publish/4784259,这是 less 工作原理的概览图。警告!它需要使用 v2 更改进行更新。