如何使用 -O2 选项优化 Less 代码

How to optimize Less code using the -O2 option

found this answer关于如何编译less文件,优化(-O2)和压缩(-x)它们:

lessc -x -O2 path/to/assets/main.less > path/to/output.css

我全局安装了 less (npm install -g less),但 -O2 似乎没有像预期的那样被解释:

Unable to interpret argument O2 - if it is a plugin (less-plugin-O2), make sure that it is installed under or at the same level as less

我该如何解决这个错误?

您对 -02 选项有什么期望?它在最新版本的 Less 中不再可用。

来自 Less v1.5:

-------------------------- Deprecated ----------------
-O0, -O1, -O2 Set the parser's optimization level. The lower the number, the less nodes it will create in the tree. This could matter for debugging, or if you want to access the individual nodes in the tree.

-

I expect that if I do: h1 { font-weight: 300; } h2 { font-weight: 300; }, then, after compilation, I have: h1, h2 { font-weight: 300; }. That's why I understood that -O2 was doing. Is there any replacement for that?

我想知道 -O2 是否确实这样做了。但是 clean-css 可以满足您的要求。

您可以在启用 advanced 选项的情况下尝试 https://github.com/less/less-plugin-clean-css

运行 npm install less-plugin-clean-css 之后就可以使用 lessc file.less --clean-css="advanced".

echo "h1 { font-weight: 300; } h2 { font-weight: 300; }" | lessc --clean-css="advanced" -

输出到控制台:

h1,h2{font-weight:300}

另请参阅:How to keep duplicate properties in compiled CSS file when use LESS?

由于 Less 的第 2 版编写您自己的插件很容易,请参阅:http://lesscss.org/usage/#plugins-for-plugin-authors. You can write a plugin for any postprocess such compressing, minifying and so on, other examples: https://github.com/less/less-plugin-autoprefix, https://github.com/bassjobsen/less-plugin-pleeease

您可以安装旧版本

npm install less@1.5 -g

它是在 Eclipse 4.4.2 中用于 Windows 的解决方案。