Skip to content

An API for plugins (the official thread) #1861

Closed

Description

@Soviut

There has been a lot of discussion about an API to create plugins for LESS. Let this be the official thread where said API and plugin mechanics be discussed!

(This is continued from #1483 in case anyone goes there first)

Activity

  1. Soviut commented on Feb 10, 2014

    @Soviut
    Author

    The first thing I can think of is that the plugin system is going to need several entry points or hooks. The first two I can think of are pre-compile and post-compile hooks. These would be useful for conditional blocks before compiling or adding vendor prefixes after compiling.

    Once we delve into the core, a pre and post hook for each stage of the compilation process would probably be a good idea. If only to be able to alert external listeners that a stage has begun or completed.

    Finally, hooks when each node along the AST tree seem logical.

  2. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    Thanks @Soviut! You're on top of it!

    Here are a few general (non-platform-specific) conventions I'd like to see:

    • Plugins are easily registered with Less.js
    • Plugins have a light and readable signature
    • Plugins should always follow a single-responsibility pattern. libraries can still combine and consume plugins to create richer applications and extensions, but the rule of thumb should be "one thing, and one thing only".
    • The core Less.js team should provide generic utilities to be used in plugins, as well as documentation, examples and best-practices for creating them.
  3. Soviut commented on Feb 10, 2014

    @Soviut
    Author

    Plugins should have a very well defined naming convention, something along the lines of jquery plugins.

    less.autoprefixer.js
    

    or

    lessjs.autoprefixer.js
    

    Personally, I prefer the first since it reads far better, especially when you take the .js extension into account as part of the name,

  4. Soviut commented on Feb 10, 2014

    @Soviut
    Author

    Plugins should have an explicit manifest, similar to package.json in npm. This doesn't necessarily have to be an external file, it may be better suited to an object within the plugin on a reserved variable.

    The main reason for this would be to allow the plugin to explain whether it's suitable for browser compilation, server compilation, or both. Version information and other details may also be worth adding, but that may begin to add unnecessary clutter.

  5. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    Yeah, a naming convention is definitely something to consider. The main advantage is for indexing/search, as with other projects like Yeoman, jQuery, Grunt and Gulp. But it doesn't have to be in the name of the project, it can also be a registration system and/or keywords in package.json (for node.js plugins), or other methods.

    Ultimately some plugins won't conform to this, and shouldn't necessarily have to. So let's just be pragmatic and creative about the approach.

  6. lukeapage commented on Feb 10, 2014

    @lukeapage
    Member

    My plan was that plugins would be seperate repos and less would scan for those repos begining less-plugin* and then use them.

    So far I have just exposed a plugins option which is an array of visitors, following the internal format for visitors.

    Its all great other people having input on plugins but unless someone else has time to help implement something different, a small expansion on the above is about as far an API as people are going to get.

    I'm of course happy to change any naming or anything else - I already discussed with Jon about the naming of the core plugins repo and thats yet to change.

    So please understand the code already outstanding. References.

    https://github.com/less/less-plugins.js
    https://github.com/less/less.js/blob/master/lib/less/parser.js#L557
    less/less-plugin-inline-urls#1

    and perhaps the last issue over the naming could do with some good ideas, although @jonschlinkert I think has made a good start.

  7. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    it may be better suited to an object within the plugin on a reserved variable.

    Yeah, that may not be a bad way to go. We have lots of other great libraries out there to look at for examples. But just to emphasize my last point... I think plugins should consist of code that - whenever possible - is usable outside of the Less.js ecosystem - so whatever "register" signature we use should be promoted as a wrapper for more generalized code. Of course, there will be many exceptions to this, when developers need to create something that will only work with Less.js, but exceptions shouldn't drive the rule.

    I think express middleware, gulp plugins and handlebars helpers (in particular) are great examples.

  8. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    all good points, @lukeapage. Maybe it would be best if we just look at this thread as being focused on a best-case scenario, not an expectation (which I don't think anyone has anyway)

  9. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    I already discussed with Jon about the naming of the core plugins repo and thats yet to change.

    did we decide that was going to change? sorry I don't remember

  10. Soviut commented on Feb 10, 2014

    @Soviut
    Author

    Regarding modularity, Grunt provides a good example of how to wrap existing tools in a thin wrapper so they're compatible with the core. However, the do maintain a good naming convention for plugins grunt-name and for core plugins grunt-contrib-name. So I would at least propose naming the wrappers with a less prefix.

  11. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    Grunt provides a good example of how to wrap existing tools in a thin wrapper

    Yeah, that's definitely the goal with Grunt plugins, to make them thin wrappers. But a couple things to consider. Grunt doesn't require names to follow that convention (see assemble, they just encouraged it initially, but the Gruntfile doesn't care what a plugin is named as long as it's registered.

    Also, Grunt is a task runner that offers a declarative config and extensive API for "wrapping" other libs, but (unless we're thinking differently here, which might be good) Less.js won't be "running" anything.

    Rather, Less.js just needs to expose an API for registering plugins so that other tools like Grunt and Gulp can consume Less.js along with the plugins that should be registered. meaning that any naming convention would be a convenience for finding plugins (by users, not Less.js). I think that Less.js itself should care about plugin names as much as it does about the name of a file referenced in an @import statement.

    But I do agree that we should "encourage" a naming convention for Less.js plugins so that they are easier to find on npm, bower etc

  12. Soviut commented on Feb 10, 2014

    @Soviut
    Author

    Agreed, I only meant we should establish an official naming convention, not that it should be strictly enforced. It's just very difficult to establish conventions like this after the fact.

  13. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    👍

  14. matthew-dean commented on Feb 10, 2014

    @matthew-dean
    Member

    My plan was that plugins would be seperate repos and less would scan for those repos begining less-plugin* and then use them.

    Interesting. I assumed that libraries might package a JavaScript file (or files) along with their code, and then you might have something like in the config json file:

    {
      plugins: [js/myLessPlugin.js, ...]
    }
    

    And then Less always checks for options.json for less config or plugin references, and loads it first.

    If the JS isn't distributed and lives on Github, doesn't it imply an internet connection is required just to compile? Or just on first run?

  15. jonschlinkert commented on Feb 10, 2014

    @jonschlinkert
    Contributor

    @matthew-dean, I was thinking similar regarding:

    {
      plugins: ['plugins/*.js']
    }
    

    except that I don't think Less.js should have to search for, parse and load JSON config files. It would be much more powerful for the API to allow registering plugins directly so that anyone could implement config loading however they wanted.

    For example, the plugin signature might look something like:

    var less = require('less');
    module.exports.lessPlugin = function(Less, options) {
      function loader(config, opts) {
        // do something
      }
      return loader;
    };

    or

    module.exports = function (options) {
      var less = require('less');
    
      less.registerPlugin('loader', function (config, opts) {
        // do something
      });
    };

    The Less.js API would only tell devs how to register these plugins, e.g. the plugin signature, and can we pass an object of plugins, or an array?, etc

    I think Handlebars helpers are a great example of how plugins can be "registered". Handlebars provides the API and conventions, and 3rd party libs decide how they want to register those helpers.

  16. 13 remaining items

  17. lukeapage commented on Feb 23, 2014

    @lukeapage
    Member
    plugin = {
        initialise: function(less) {
            // gives the less object to allow setting up things, such as getting a reference to create a visitor object and
            // less.Parser.environment to access environment specifics, so a plugin can be environment agnostic
        },
        type: function() {
            // return "function" or "visitor" or "importer" or "log" or an array of types
        },
        getFunctions() {
            // returns an object { function-name: function }
        },
        getVisitors() {
            // returns an array of visitors
        },
        getImporters() {
            // returns an array of importers
        },
        getLogs() {
            // returns an array of logs
        }
    };
    visitor = {
        isReplacing: true/false, // as per normal visitor
        name: "MyVisitor",         // to match system visitors
        getPosition: function() {
            // returns "pre" or "post" followed by step name
            // e.g. return "preEval"
            // "postToCSS"
        },
        // and all the visit Functions as per a less visitor
    };
    importer = {
        processFile: // follows the same api as the environment loadFile I'm working on 
    }
    log = {
        log: function(message, level) {
        }
    }
    
  18. lukeapage commented on Feb 23, 2014

    @lukeapage
    Member

    Just wondering whether name and isReplacing on a visitor should be changed to functions or if getPosition should be a property. I don't see any reason why any of the values would be dynamic

  19. rjgotten commented on Feb 24, 2014

    @rjgotten
    Contributor

    At the very least, I would agree to not do this:

    @import (plugin) "../plugins/my-plugin.js";
    

    That doesn't feel right to me. It's a short-term and problematic solution, and a broader file-based "options set" would be a smarter one.

    It seems like that statement does not mesh well with your previous statement:

    Be careful that we don't make the assumption that the Less consumer (the person writing Less) both has access to lessc and knows how to use it.

    Mind explaining why you'd be opposed to using an import statement and why it would be "a short-term and problemetic solution", because frankly; I'm not seeing it. The absolute easiest and most foolproof way to ensure a plugin is loaded is by picking it up as an import as part of the compilation process. Completely hands-off, no user-configuration required.

  20. jonschlinkert commented on Feb 24, 2014

    @jonschlinkert
    Contributor

    @lukeapage looks like a great start!

  21. matthew-dean commented on Feb 25, 2014

    @matthew-dean
    Member

    @rjgotten Interestingly, after I wrote that, and wrote up #1893, hoping to address the config-file based scenario, I realized that it was a somewhat problematic solution as well, and it occurred to me what you just wrote, so I'm glad you brought it up.

    What I saw as I was architecting is that if I import, say, a future version of bootstrap, and say it relies on a plugins to parse, then it's destined to break. And then, I, as a user, will ask, "Why did it break?" and they'll sigh and point out that I didn't follow the precise instructions of how to define the plugin in my less options file.

    So, I think that in my zeal to have an options file (and to have less inline JavaScript), which would be absolutely great for developers, I ignored the simplicity and appeal of this option, which is great for library authors and average users, since they don't have to think about it.

    The absolute easiest and most foolproof way to ensure a plugin is loaded is by picking it up as an import as part of the compilation process. Completely hands-off, no user-configuration required.

    My explanation therefore is that you are, in fact, correct. Thanks for bringing it up again, because it really is a good idea.

  22. matthew-dean commented on Feb 25, 2014

    @matthew-dean
    Member

    The other thing to keep in mind (and I sincerely hope I didn't also miss if someone said this), is to think about designing API hooks so that plugins are never "redefining" function pointers. So, for example, in the past, the semi-official way of changing the file import method was literally overriding the function. But we should consider ways to make plugins happy with each other. So that my custom plugin doesn't interfere with something else that an external library's custom plugin is doing.

  23. rjgotten commented on Feb 26, 2014

    @rjgotten
    Contributor

    @matthew-dean The problem with plugins overwriting each other (or overwriting core functions) is interesting. If you go the way of @import-ing plugins, then maybe you can make the default behavior to scope plugin presence to the importing sheet only. That could cut back dramatically on the number of cross-sheet plugin name collisions.

    Maybe you should allow for a single override level on top of core functions and then offer a way inside an overriding plugin to call back to the 'base' core implementation. That kind of infastructure would allow consumers to extend existing core functions with the aim of prototyping new behavior, or monkey-patching bugs.

  24. calvinjuarez commented on Feb 26, 2014

    @calvinjuarez
    Member

    As a non-lessc, pre-processor-style, CodeKit LESS user, I'm very in favor of a directive in the LESS file itself. I'd prefer to have a separate directive keyword (like, say @plugin), because I feel like the function of a plugin (augmenting how LESS works) is different to imports (affecting the output CSS). That's my 2¢.

  25. matthew-dean commented on Feb 27, 2014

    @matthew-dean
    Member

    @rjgotten That's an interesting and clever idea, but it seems like it would be technologically challenging. I'm not exactly sure how you'd scope plugins for only part of the import process. I meant more that it would be more like the evolution of event registration in browsers. Originally, there was direct assignment (overriding) of a single function, but eventually, multiple handlers could be added. I'm not sure it's a perfect metaphor, but that idea of plugin registration that adds functionality (and language features) being designed to not cause conflicts.

    @calvinjuarez Thanks for the feedback. And that's a good point. Depending on how we do plugins, it might even be the first thing that should be "executed", even before imports in the same sheet, in case a plugin adds a language feature, say, for imports.

  26. censys-git commented on Apr 22, 2014

    @censys-git

    Just added a feature request for file operations plugin. Such as "openFile", "createFile", and so on. Allows situations where server-side environment does not provide window, dom or document object and uses it's own file APIs for getting/setting files and directories, etc. (including URI versus file ID references where files cannot be accessed via a URI/path and only by a system internal ID). These may be lower level APIs than is being discussed, but at a minimum the ability to overwrite the read/write file operations is highly desired/needed for my use-case (using in a Software-as-a-Service/Hosted environment where javaScript scripts can be run server side but are limited to using vendor specific APIs for file operations or access to lower level server environment).

  27. lukeapage commented on Oct 9, 2014

    @lukeapage
    Member

    Just read through the whole issue again to check I wasn't missing anything and that everything I've added in v2 provides (or does not preclude adding in the future) anything suggested here.

    Here is some documentation I just wrote that I will put onto the site once v2 is released.

    You can provide feedback though I am interested more in things that won't work or breaking things than things missing (add it yourself!) or stylistic changes (given the enormous time I've spent on it I feel I have the right to last say!). But I will try and consider everything.

    Plugins

    How do I use a plugin ?

    Lessc

    If you are using lessc, the first thing you need to do is install that plugin. We reccommend the plugin starts "less-plugin" though that isn't required. For the clean css plugin you would install npm install less-plugin-clean-css.

    To use the plugin, if you specify a unrecognised option, we attempt to load that, for example

    lessc --clean-css="advanced"
    

    Will use the plugin you just installed. You can also be more direct, for example

    lessc --plugin=path_to_plugin=options
    

    In Code

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

    var myPlugin = require("my-plugin");
    less.render(myCSS, { plugins: [myPlugin] })
       .then(function(css) {
        },
        function(error) {
        });
    

    In the browser

    Plugin authors should provide a javascript file, just include that in the page before the less.js script.

    For Plugin Authors

    Less supports some entry points that allow an author to integrate with less. We may add some more in the future.

    The plugin itself has a very simple signtaure, like this

    {
        install: function(less, pluginManager) {
        },
        minVersion: [2, 0, 0] /* optional */
    }
    

    So, the plugin gets the less object, which in v2 has more classes on it (making it easy to extend), a plugin manager which provides some hooks to add visitors, file managers and post processors.

    If your plugin supports lessc, there are a few more details and the signature looks like this

    {
        install: function(less, pluginManager) {
        },
        setOptions: function(argumentString) { /* optional */
        },
        printUsage: function() { /* optional */
        },
        minVersion: [2, 0, 0] /* optional */
    }
    

    The additions are the setOptions function which passes the string the user enters when specifying your plugin and also the printUsage function which you should use to explain your options and how the plugin works.

    Here are some example repos showing the different plugin types
    post-processor: https://github.com/less/less-plugin-clean-css
    visitor: https://github.com/less/less-plugin-inline-urls
    file-manager: https://github.com/less/less-plugin-npm-import

    Note: Plugins are different from creating a version of less for a different environment but they do have similarities, for example node provides 2 file managers by default and browser provides one and that is the main step in getting less to run within a specific environment. The plugin allows you to add file managers.

  28. lukeapage commented on Oct 12, 2014

    @lukeapage
    Member

    Closing as implemented in v2. Please raise new functionality requests in new issues and obviously I'll still listen to this thread if there is any feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions