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