require() best practices

Posted on
  • I've seen a lot of apps repeatedly use code like :


    with the same module over and over. Is that a bad thing? I would have thought something like:

    var mod = require("module");
    // ...

    would be better if you're using the same module over and over? This is particularly noticeable for modules like "locale".

    The Modules page doesn't cover this, but uses the first convention. The entry for require uses the second as the example.

    I'd prefer the second (assigning to a variable), but I'd like confirmation that is best.

  • The second method is a smidge faster, but not too much - and it does use one more variable, so really it's personal opinion.

    Once the module has been loaded it's 'cached' and subsequent calls to require("module") will just do a lookup, so it's not like the whole thing is being loaded in each time.

  • Thanks. That's all good to know.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

require() best practices

Posted by Avatar for andrewg_oz @andrewg_oz