Frage

I'm writing my first CommonJS module.

Is it common practice to define a CommonJS module in a scoped function, like so

(function() {
  module.exports = ...
})();

or is there no value in this?

War es hilfreich?

Lösung

No, that's not necessary. Surrounding all of your code in an immediately invoked function expressions (iife) is a solution for browser-based problems.

If your module is used in Node.JS, the module will be executed in its own scope. See their docs page for examples, none of which use iife. However, if you're using a CommonJS module in a browser, you will need to bundle your CommonJS modules with a tool like watchify or commonjs-everywhere. These tools put each module definition into its own enclosing function anyway, achieving the same protection as iife.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top