JavaScript does not have built-in support for modules, but the community has created impressive workarounds. To manage modules, you can use so-called package managers, which handle discovery, installation, dependency management, and more.
The two most important (and unfortunately incompatible) standards for JavaScript modules are:
The dominant incarnation of this standard is Node.js modules (Node.js modules have a few features that go beyond CJS). Its characteristics include:
The most popular implementation of this standard is RequireJS. Its characteristics include:
eval()
or a static compilation step
When it comes to package managers, npm (Node Packaged Modules) is the canonical choice for Node.js. For browsers, two options are popular (among others):
For normal web development, you should use a module system such as RequireJS or Browserify. However, sometimes you just want to put together a quick hack. Then the following simple module pattern can help:
var
moduleName
=
function
()
{
function
privateFunction
()
{
...
}
function
publicFunction
(...)
{
privateFunction
();
otherModule
.
doSomething
();
// implicit import
}
return
{
// exports
publicFunction
:
publicFunction
};
}();
The preceding is a module that is stored in the global variable moduleName
. It does the following:
otherModule
)
privateFunction
publicFunction
To use the module on a web page, simply load its file and the files of its dependencies via <script>
tags:
<script
src=
"modules/otherModule.js"
></script>
<script
src=
"modules/moduleName.js"
></script>
<script
type=
"text/javascript"
>
moduleName
.
publicFunction
(...);
</script>
If no other module is accessed while a module is loaded (which is the case for moduleName
), then the order in which modules are loaded does not matter.
Here are my comments and recommendations: