- Notifications
You must be signed in to change notification settings - Fork125
commonjs
The CommonJS group defined a module format to solveJavaScript scope issues by making sure each moduleis executed in its own namespace.
This is achieved by forcing modules to explicitly exportthose variables it wants to expose to the "universe",and also by defining those other modules required toproperly work.
To achieve this CommonJS gives you two tools:
- the
require()function, which allows to import a given module into the current scope. - the
moduleobject, which allows you to export something from the current scope.
The mandatory hello world example:
Here is an example without CommonJS:
We will define a value in a script file namedsalute.js.This script will contain just a value that will be used in other scripts:
// salute.jsvarMySalute="Hello";
Now, in a second file namedworld.js, we aregoing to use the value defined insalute.js.
// world.jsvarResult=MySalute+" world!";
As it is,world.js will not work asMySalute is not defined.We need to define each script as a module:
// salute.jsvarMySalute="Hello";module.exports=MySalute;
// world.jsvarResult=MySalute+"hello world!";module.exports=Result;
Here we make use of the special objectmodule and place a reference of ourvariable intomodule.exports so the CommonJS module system knows this isthe object of our module we want to show to the world.salute.js disclosesMySalute, andworld.js disclosesResult.
We're near but there's still a step missing: dependency definition.We've already defined every script as an independent module, butworld.jsstill needs to know who definesMySalute:
// salute.jsvarMySalute="Hello";module.exports=MySalute;
// world.jsvarMySalute=require("./salute");varResult=MySalute+"world!";module.exports=Result;
Note that we didn't use the full filenamesalute.js but./salute when callingrequire, so you can omit the extension of your scripts../ means that thesalute module is in the same directory as theworld module.
// moduleA.jsmodule.exports=function(value){returnvalue*2;}
// moduleB.jsvarmultiplyBy2=require('./moduleA');varresult=multiplyBy2(4);
webpack 👍