Common practice to use scoped functions for CommonJS modules, or unnecessary?

StackOverflow https://stackoverflow.com/questions/23528616

  •  17-07-2023
  •  | 
  •  

Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top