先写插件在浏览器中使用。您使用以下代码创建插件:
var TwoTimesAndTen = {
install: function(less) {
less.functions.functionRegistry.add('twotimesandten' ,function(input) { return new(less.tree.Anonymous)(input.value * 2 + 10);} );
}
};
less = {
env: "development",
plugins: [TwoTimesAndTen]
};
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.1.0/less.min.js"></script>
请注意,您应该始终将函数的名称写成小写。
要将上述代码用于命令行编译器,您应该创建一个名为less-plugin-twotimesandten/index.js
. 该文件应包含以下代码:
var TwoTimesAndTen = {
install: function(less) {
less.functions.functionRegistry.add('twotimesandten' ,function(input) { return new(less.tree.Anonymous)(input.value * 2 + 10);} );
}
};
module.exports = TwoTimesAndTen;
然后,您可以在控制台中运行以下命令:
echo '@start: 10; .test { result:twotimesandten(@start); }' | lessc --plugin=less-plugin-twotimesandten/index.js -
以上将输出:
.test {
result: 30;
}
要安装此插件以供全球使用,您应该创建第二个名为less-plugin-twotimesandten/package.json
. package.json 至少应包含以下代码行:
{
"name": "less-plugin-twotimesandten",
"version": "0.0.1",
"description": "twotimesandten plugin for less.js",
"main": "index.js"
}
保存 package.json 文件后,您可以在控制台中运行以下命令:
npm install less-plugin-twotimesandten
确保首先在less-plugin-twotimesandten
目录之外导航。在前面的命令less-plugin-twotimesandten
中是您的插件的路径。
现在您可以运行以下命令:
echo '@start: 10; .test { result:twotimesandten(@start); }' | lessc --twotimesandten -
要编写一个同时运行客户端和服务器端的插件,您应该阅读:http ://caolanmcmahon.com/posts/writing_for_node_and_the_browser/ (请随时为https://github.com/less/less-meta/issues/5做出贡献也)。
重写你的内容less-plugin-twotimesandten/index.js
如下:
(function(exports){
exports.install= function(less) {
less.functions.functionRegistry.add('twotimesandten' ,function(input) { return new(less.tree.Anonymous)(input.value * 2 + 10);} );
};
})(typeof exports === 'undefined'? this['TwoTimesAndTen']={}: exports);
以上不会改变命令行的使用。对于浏览器使用,您现在可以使用以下代码:
<script src="less-plugin-twotimesandten/index.js"></script>
<script>
less = {
env: "development",
plugins: [TwoTimesAndTen]
};
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.1.0/less.min.js"></script>