Node-模块化

模块化


为了解决文件之间的依赖,模块化是一种约定好的规范。
模块化规范是一种明文的约定,开发者都按照规范来写代码,减少沟通成本,极大的方便了各模块之间的相互调用。

一、 了解 CommonJS 规范

  1. 作用:是一套 Javascript 的模块化规范,规定了 模块的特性各模块之间如何相互依赖

  2. 用途:Node.js 中使用了 CommonJS 规范;

  3. 特点:同步加载模块;不适合在浏览器端使用;浏览器端使用 AMD / CMD。

  4. CommonJS规范都定义了哪些内容:wiki 对于 Modules 的描述

4.1 如何引入 In a module, there is a free variable "require", that is a Function.
4.2 如何暴露给别人使用In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.
4.3 必须有一个变量module 。In a module, there must be a free variable "module", that is an Object.

二、 模块作用域 和 全局作用域

在Node.js中有两个作用域,分别是 全局作用域模块作用域

  1. 全局作用域: 使用 global 来访问,类似于浏览器中的 window
  2. 每个 Javascript 文件,都是一个单独模块,每个模块都有自己独立的作用域,因此:模块中的成员,默认无法被其它模块访问。
  3. 默认在 Node 中,每一个 JS 文件中定义的 方法、变量,都是属于 模块作用域的.

挂载到global

var b = 20;
global.b = b; 
global.say = function () {
  console.log('这是挂载到全局的 say 方法');
}

转载于:https://www.jianshu.com/p/6fb38b916cd9

猜你喜欢

转载自blog.csdn.net/weixin_33810302/article/details/91319950