-
Notifications
You must be signed in to change notification settings - Fork 0
commonjs.cn
The CommonJS group defined a module format to solve JavaScript scope issues by making sure each module is executed in its own namespace.
CommonJS 工作组通过定义一种模块格式来解决 JavaScript 的作用域问题,其原理是让每个模块都运行在各自的命名空间里。
This is achieved by forcing modules to explicitly export those variables it wants to expose to the "universe", and also by defining those other modules required to properly work.
这一目标的达成,是通过强制每个模块都必需显式地向外导出欲暴露出去的变量,以及定义了引用其它模块后能正确运行的方式。
To achieve this CommonJS gives you two tools: 为了达到这一目的,CommonJS 提供了两个工具:
-
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. -
require函数,允许将给定的模块引入到当前作用域 -
module对象,用于从当前作用域导出数据
The mandatory hello world example:
例行的 hello world 样例:
Here is an example without CommonJS:
下面是一个没有使用 CommonJS 的例子。
We will define a value in a script file named salute.js.
This script will contain just a value that will be used in other scripts:
在 salute.js 中定义一个值,此脚本仅包含一个于其它脚本使用的值:
// salute.js
var MySalute = "Hello";Now, in a second file named world.js, we are going to use the value defined in salute.js.
然后,在另一个文件 world.js 中使用 salute.js 中定义的值。
// world.js
var Result = MySalute + " world!";As it is, world.js will not work as MySalute is not defined.
We need to define each script as a module:
不言而喻,world.js不会正常工作,因为MySalute没有定义
// salute.js
var MySalute = "Hello";
module.exports = MySalute;// world.js
var Result = MySalute + "world!";
module.exports = Result;Here we make use of the special object module and place a reference of our
variable into module.exports so the CommonJS module system knows this is
the object of our module we want to show to the world.
salute.js discloses MySalute, and world.js discloses Result.
这里我们使用了module对象,并把我们的变量赋给了 module.exports,这样 CommonJS 模块系统知道我们的模块希望对外提供给这些值。salute.js 暴露了 MySalute,world.js 暴露了 Result
We're near but there's still a step missing: dependency definition.
We've already defined every script as an independent module, but world.js
still needs to know who defines MySalute:
还差一步我们就成功了:依赖的定义。
我们已经将每个脚本都定义成单独的模块,不过world.js仍需要知道MySalute的来源。
// salute.js
var MySalute = "Hello";
module.exports = MySalute;// world.js
var MySalute = require("./salute");
var Result = MySalute + "world!";
module.exports = Result;Note that we didn't use the full filename salute.js but ./salute when calling
require, so you can omit the extension of your scripts. ./ means that the salute module is in the same directory as the world module.
注意,调用require的时候我们并没有使用salute.js这个全称,而是用了./salute,因为可以忽略脚本的扩展名。./声明salute这个模块与world模块处于同一目录。
// moduleA.js
module.exports = function( value ){
return value*2;
}// moduleB.js
var multiplyBy2 = require('./moduleA');
var result = multiplyBy2( 4 );此篇翻译参照了liunian/webpack-doc对应的文档