Javascript的模块管理 CMD AMD ES7等

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Javascript的模块管理 CMD AMD ES7等脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

一 Commonjs

开始js是垃圾,但随着时代的发展、业务的进步,js变得越来越重要,但js涉及之初就是用来打杂的,有缺陷如下:

  1. JavaScript has no module System. To compose JavaScript scripts, they must be eITher managed in HTML, concatenated, injected, or manually fetched and evaluated. There is no native facility for scoPE isolation or dependency management.
  2. JavaScript has no standard library. It has a browser API, dates, and math, but no file system API, much less an IO stream API or PRimordial types for binary data.
  3. JavaScript has no standard interfaces for things like Web servers or databases.
  4. JavaScript has no package management system that manages dependencies and automatically installs them, except JSAN (not to be confused with JSON), which falls short for scope isolation.

简单翻译下:

  1. 没有模块系统
  2. 没有标准库、没有文件、没有IO系统
  3. 没有标准接口,用来做服务器或者数据库
  4. 没有依赖包管理系统。

所以mozila的工程师希望来解决这个问题

“What I’m describing here is not a technical problem. It’s a matter of people getting together and making a decision to step forward and start building up something Bigger and cooler together.”

这并不是一个技问题,而是为了便于更多人合作...

所以就有了commonjs,定义了这些概念,而nodejs实现了这个标准。
CommonJS定义的模块分为:{模块引用(require)} {模块定义(exports)} {模块标识(module)}
比如这个样子:

// foo.js
module.exports = function(x) {
  console.LOG(x);
};

// main.js
VAR foo = require("./foo");
foo("Hi");

看似完美的解决了模块问题,但在浏览器模式下是不行的,假设我们有如下这段代码

var math = require('math');
math.add(2, 3);

问题1:math.add会被阻塞掉,必须在require完成之后再执行
问题2:即使能够异步加载,但你如何能够知道什么时候加载完毕,什么时候能够执行完么?

二 AMD

(Asynchronous Module Definition) 异步模块加载
这里不得不说到我们的requirejs,它有两个参数 
 

require([module], callback);

第一个表示依赖的模块,第二个就是具体的回掉了,比如上上述的代码

require(['math'], function (math) {
    math.add(2, 3);
  });

三 ES6

ES6中的模块最大的特点就是静态,即在编译时就确定依赖关系,ES6中会自然采用严格模式

  1. 变量必须声明后再使用
  2. 函数的参数不能有同名属性,否则报错
  3. 不能使用with语句
  4. 不能对只读属性赋值,否则报错
  5. 不能使用前缀0表示八进制数,否则报错
  6. 不能删除不可删除的属性,否则报错
  7. 不能删除变量delete prop,会报错,只能删除属性delete global[prop]
  8. eval不会在它的外层作用域引入变量
  9. evalarguments不能被重新赋值
  10. arguments不会自动反映函数参数的变化
  11. 不能使用arguments.callee
  12. 不能使用arguments.caller
  13. 禁止this指向全局对象
  14. 不能使用fn.caller和fn.arguments获取函数调用的堆栈
  15. 增加了保留字(比如protectedstaticinterface

参考:http://www.cnblogs.com/chengu...

脚本宝典总结

以上是脚本宝典为你收集整理的Javascript的模块管理 CMD AMD ES7等全部内容,希望文章能够帮你解决Javascript的模块管理 CMD AMD ES7等所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。