脚本宝典收集整理的这篇文章主要介绍了

前端模块化详解(完整版)

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。
<p><code></p> <h2 id="articleHeader0">前言</h2> <p>在JavaScript发展初期就是为了实现简单的页面交互逻辑,寥寥数语即可;如今CPU、浏览器性能得到了极大的提升,很多页面逻辑迁移到了客户端(表单验证等),随着web2.0时代的到来,Ajax技术得到广泛应用,<a href="http://www.js-code.com/tag/jquery" title="jQuery" target="_blank">jQuery</a>等前端库层出不穷,前端代码日益膨胀,此时在JS方面就会考虑使用模块化规范去管理。<br />本文内容主要有理解模块化,为什么要模块化,模块化的优缺点以及模块化规范,并且介绍下开发中最流行的CommonJS, AMD, ES6、CMD规范。本文试图站在小白的角度,用通俗易懂的笔调介绍这些枯燥无味的概念,希望诸君阅读后,对模块化编程有个全新的认识和理解!</p> <p><strong>建议下载本文源代码,自己动手敲一遍,请猛戳<a href="https://github.com/ljianshu/Blog" rel="nofollow noreferrer" target="_blank">GitHub个人博客</a></strong></p> <p><span class="img-wrap"><img data-src="/img/remote/1460000017466123?w=1240&amp;h=564" src="/img/remote/1460000017466123?w=1240&amp;h=564" alt="模块化规范" title="模块化规范" style="cursor: pointer; display: inline;"></span></p> <h2 id="articleHeader1">一、模块化的理解</h2> <h3 id="articleHeader2">1.什么是模块?</h3> <ul> <li>将一个复杂的程序依据一定的规则(规范)封装成几个块(文件), 并进行组合在一起</li> <li>块的内部数据与实现是私有的, 只是向外部暴露一些接口(方法)与外部其它模块通信</li> </ul> <h3 id="articleHeader3">2.模块化的进化过程</h3> <ul> <li> <p><strong>全局<a href="http://www.js-code.com/tag/function" title="function" target="_blank">function</a>模式 : 将不同的功能封装成不同的全局函数</strong></p> <ul> <li>编码: 将不同的功能封装成不同的全局函数</li> <li>问题: 污染全局命名空间, 容易引起命名冲突或数据不安全,而且模块成员之间看不出直接关系</li> </ul> </li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="function m1(){ //... } function m2(){ //... }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs actionscript"><code><span class="hljs-function"><span class="hljs-keyword"><a href="http://www.js-code.com/tag/function" title="浏览关于“function”的文章" target="_blank" class="tag_link">function</a></span> <span class="hljs-title">m1</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">//...</span> } <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">m2</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">//...</span> }</code></pre> <ul> <li> <p><strong><a href="http://www.js-code.com/tag/name" title="name" target="_blank">name</a>space模式 : 简单对象封装</strong></p> <ul> <li>作用: 减少了全局变量,解决命名冲突</li> <li>问题: 数据不安全(外部可以直接修改模块内部的数据)</li> </ul> </li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="let myModule = { data: 'www.baidu.com', foo() { console.log(`foo() ${this.data}`) }, bar() { console.log(`bar() ${this.data}`) } } myModule.data = 'other data' //能直接修改模块内部的数据 myModule.foo() // foo() other data" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword"><a href="http://www.js-code.com/tag/let" title="浏览关于“let”的文章" target="_blank" class="tag_link">let</a></span> myModule = { <span class="hljs-attr">data</span>: <span class="hljs-string">'www.baidu.com'</span>, foo() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`foo() <span class="hljs-subst">${<span class="hljs-keyword"><a href="http://www.js-code.com/tag/this" title="浏览关于“this”的文章" target="_blank" class="tag_link">this</a></span>.data}</span>`</span>) }, bar() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`bar() <span class="hljs-subst">${<span class="hljs-keyword">this</span>.data}</span>`</span>) } } myModule.data = <span class="hljs-string">'other data'</span> <span class="hljs-comment">//能直接修改模块内部的数据</span> myModule.foo() <span class="hljs-comment">// foo() other data</span></code></pre> <p>这样的写法会暴露所有模块成员,内部状态可以被外部改写。</p> <ul> <li> <p><strong>IIFE模式:匿名函数自调用(闭包)</strong></p> <ul> <li>作用: 数据是私有的, 外部只能通过暴露的方法操作</li> <li>编码: 将数据和行为封装到一个函数内部, 通过给w<a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a><a href="http://www.js-code.com/tag/do" title="do" target="_blank">do</a>w添加属性来向外暴露接口</li> <li>问题: 如果当前这个模块依赖另一个模块怎么办?</li> </ul> </li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>="// <a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>dex.html文件<br /> <script type=&quot;text/javascript&quot; src=&quot;module.js&quot;></script><br /> <script type=&quot;text/javascript&quot;> myModule.foo() myModule.bar() console.log(myModule.data) //<a href="http://www.js-code.com/tag/undefined" title="undefined" target="_blank">undefined</a> 不能访问模块内部数据 myModule.data = 'xxxx' //不是修改的模块内部的data myModule.foo() //没有改变 </script>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code>// <a href="http://www.js-code.com/tag/in" title="浏览关于“in”的文章" target="_blank" class="tag_link">in</a>dex.html文件 <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"<a href="http://www.js-code.com/tag/text" title="浏览关于“text”的文章" target="_blank" class="tag_link">text</a>/<a href="http://www.js-code.com/tag/java" title="浏览关于“java”的文章" target="_blank" class="tag_link">java</a>script"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"module.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="javascript"> myModule.foo() myModule.bar() <span class="hljs-built_in">console</span>.log(myModule.data) <span class="hljs-comment">//<a href="http://www.js-code.com/tag/undefined" title="浏览关于“undefined”的文章" target="_blank" class="tag_link">undefined</a> 不能访问模块内部数据</span> myModule.data = <span class="hljs-string">'xxxx'</span> <span class="hljs-comment">//不是修改的模块内部的data</span> myModule.foo() <span class="hljs-comment">//没有改变</span> </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// module.js文件 (function(window) { let data = 'www.baidu.com' //操作数据的函数 function foo() { //用于暴露有函数 console.log(`foo() ${data}`) } function bar() { //用于暴露有函数 console.log(`bar() ${data}`) otherFun() //内部调用 } function otherFun() { //内部私有的函数 console.log('otherFun()') } //暴露行为 window.myModule = { foo, bar } //ES6写法 })(window)" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// module.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><a href="http://www.js-code.com/tag/window" title="浏览关于“window”的文章" target="_blank" class="tag_link">window</a></span>) </span>{ <span class="hljs-keyword">let</span> data = <span class="hljs-string">'www.baidu.com'</span> <span class="hljs-comment">//操作数据的函数</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//用于暴露有函数</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`foo() <span class="hljs-subst">${data}</span>`</span>) } <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//用于暴露有函数</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`bar() <span class="hljs-subst">${data}</span>`</span>) otherFun() <span class="hljs-comment">//内部调用</span> } <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">otherFun</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//内部私有的函数</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'otherFun()'</span>) } <span class="hljs-comment">//暴露行为</span> <span class="hljs-built_in">win<a href="http://www.js-code.com/tag/do" title="浏览关于“do”的文章" target="_blank" class="tag_link">do</a>w</span>.myModule = { foo, bar } <span class="hljs-comment">//ES6写法</span> })(<span class="hljs-built_in">window</span>)</code></pre> <p>最后得到的结果:</p> <p><span class="img-wrap"><img data-src="/img/remote/1460000017466124?w=419&amp;h=105" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="" title="" style="cursor: pointer;"></span></p> <ul> <li><strong>IIFE模式增强 : 引入依赖</strong></li> </ul> <p>这就是现代模块实现的基石</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// module.js文件 (function(window, $) { let data = 'www.baidu.com' //操作数据的函数 function foo() { //用于暴露有函数 console.log(`foo() ${data}`) $('body').css('background', 'red') } function bar() { //用于暴露有函数 console.log(`bar() ${data}`) otherFun() //内部调用 } function otherFun() { //内部私有的函数 console.log('otherFun()') } //暴露行为 window.myModule = { foo, bar } })(window, jQuery)" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// module.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">window, $</span>) </span>{ <span class="hljs-keyword">let</span> data = <span class="hljs-string">'www.baidu.com'</span> <span class="hljs-comment">//操作数据的函数</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//用于暴露有函数</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`foo() <span class="hljs-subst">${data}</span>`</span>) $(<span class="hljs-string">'body'</span>).css(<span class="hljs-string">'background'</span>, <span class="hljs-string">'red'</span>) } <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//用于暴露有函数</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`bar() <span class="hljs-subst">${data}</span>`</span>) otherFun() <span class="hljs-comment">//内部调用</span> } <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">otherFun</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//内部私有的函数</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'otherFun()'</span>) } <span class="hljs-comment">//暴露行为</span> <span class="hljs-built_in">window</span>.myModule = { foo, bar } })(<span class="hljs-built_in">window</span>, <a href="http://www.js-code.com/tag/jquery" title="浏览关于“jQuery”的文章" target="_blank" class="tag_link">jQuery</a>)</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>=" // index.html文件<br /> <!-- 引入的js必须有一定顺序 --><br /> <script type=&quot;text/javascript&quot; src=&quot;jquery-1.10.1.js&quot;></script><br /> <script type=&quot;text/javascript&quot; src=&quot;module.js&quot;></script><br /> <script type=&quot;text/javascript&quot;> myModule.foo() </script>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code> // index.html文件 <span class="hljs-comment">&lt;!-- 引入的js必须有一定顺序 --&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"jquery-1.10.1.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"module.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="undefined"> myModule.foo() </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre> <p>上例子通过jquery方法将页面的背景颜色改成红色,所以必须先引入<a href="http://www.js-code.com/tag/jquery" title="jQuery" target="_blank">jQuery</a>库,就把这个库当作参数传入。<strong>这样做除了保证模块的独立性,还使得模块之间的依赖关系变得明显</strong>。</p> <h3 id="articleHeader4">3. 模块化的好处</h3> <ul> <li>避免命名冲突(减少命名空间污染)</li> <li>更好的分离, 按需加载</li> <li>更高复用性</li> <li>高可维护性</li> </ul> <h3 id="articleHeader5">4. 引入多个<code>&lt;script&gt;</code>后出现出现问题</h3> <ul> <li>请求过多</li> </ul> <p>首先我们要依赖多个模块,那样就会发送多个请求,导致请求过多</p> <ul> <li>依赖模糊</li> </ul> <p>我们不知道他们的具体依赖关系是什么,也就是说很容易因为不了解他们之间的依赖关系导致加载先后顺序出错。</p> <ul> <li>难以维护</li> </ul> <p>以上两种原因就导致了很难维护,很可能出现牵一发而动全身的情况导致项目出现严重的问题。<br />模块化固然有多个好处,然而一个页面需要引入多个js文件,就会出现以上这些问题。而这些问题可以通过模块化规范来解决,下面介绍开发中最流行的commonjs, AMD, ES6, CMD规范。</p> <h2 id="articleHeader6">二、模块化规范</h2> <h3 id="articleHeader7">1.CommonJS</h3> <h4>(1)概述</h4> <p>Node 应用由模块组成,采用 CommonJS 模块规范。每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。<strong>在服务器端,模块的加载是运行时同步加载的;在浏览器端,模块需要提前编译打包处理。</strong></p> <h4>(2)特点</h4> <ul> <li>所有代码都运行在模块作用域,不会污染全局作用域。</li> <li>模块可以多次加载,但是只会在第一次加载时运行一次,然后运行结果就被缓存了,以后再加载,就直接读取缓存结果。要想让模块再次运行,必须清除缓存。</li> <li>模块加载的顺序,按照其在代码中出现的顺序。</li> </ul> <h4>(3)基本语法</h4> <ul> <li>暴露模块:<code>module.<a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a>s = value</code>或<code><a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a>s.xxx = value</code> </li> <li>引入模块:<code>require(xxx)</code>,如果是第三方模块,xxx为模块名;如果是自定义模块,xxx为模块文件路径</li> </ul> <p>此处我们有个疑问:<strong>CommonJS暴露的模块到底是什么?</strong> CommonJS规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的<a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a>s属性(即module.<a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a>s)是对外的接口。<strong>加载某个模块,其实是加载该模块的module.<a href="http://www.js-code.com/tag/export" title="浏览关于“export”的文章" target="_blank" class="tag_link">export</a>s属性</strong>。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// example.js var x = 5; var addX = function (value) { return value + x; }; module.exports.x = x; module.exports.addX = addX;" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// example.js</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/var" title="浏览关于“var”的文章" target="_blank" class="tag_link">var</a></span> x = <span class="hljs-number">5</span>; <span class="hljs-keyword">var</span> addX = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/return" title="浏览关于“return”的文章" target="_blank" class="tag_link">return</a></span> value + x; }; <span class="hljs-built_in">module</span>.exports.x = x; <span class="hljs-built_in">module</span>.exports.addX = addX;</code></pre> <p>上面代码通过module.exports输出变量x和函数addX。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="var example = require('./example.js');//如果参数字符串以“./”开头,则表示加载的是一个位于相对路径 console.log(example.x); // 5 console.log(example.addX(1)); // 6" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">var</span> example = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./example.js'</span>);<span class="hljs-comment">//如果参数字符串以“./”开头,则表示加载的是一个位于相对路径</span> <span class="hljs-built_in">console</span>.log(example.x); <span class="hljs-comment">// 5</span> <span class="hljs-built_in">console</span>.log(example.addX(<span class="hljs-number">1</span>)); <span class="hljs-comment">// 6</span></code></pre> <p>require命令用于加载模块文件。<strong>require命令的基本功能是,读入并执行一个JavaScript文件,然后返回该模块的exports对象。如果没有发现指定模块,会报错</strong>。</p> <h4>(4)模块的加载机制</h4> <p><strong>CommonJS模块的加载机制是,输入的是被输出的值的拷贝。也就是说,一旦输出一个值,模块内部的变化就影响不到这个值</strong>。这点与<a href="http://www.js-code.com/tag/es6%e6%a8%a1%e5%9d%97" title="ES6模块" target="_blank">ES6模块</a>化有重大差异(下文会介绍),请看下面这个例子:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// lib.js var counter = 3; function incCounter() { counter++; } module.exports = { counter: counter, incCounter: incCounter, }; " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// lib.js</span> <span class="hljs-keyword">var</span> counter = <span class="hljs-number">3</span>; <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">incCounter</span>(<span class="hljs-params"></span>) </span>{ counter++; } <span class="hljs-built_in">module</span>.exports = { <span class="hljs-attr">counter</span>: counter, <span class="hljs-attr">incCounter</span>: incCounter, }; </code></pre> <p>上面代码输出内部变量counter和改写这个变量的内部方法incCounter。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// main.js var counter = require('./lib').counter; var incCounter = require('./lib').incCounter; console.log(counter); // 3 incCounter(); console.log(counter); // 3" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// main.js</span> <span class="hljs-keyword">var</span> counter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./lib'</span>).counter; <span class="hljs-keyword">var</span> incCounter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./lib'</span>).incCounter; <span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 3</span> incCounter(); <span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 3</span></code></pre> <p>上面代码说明,counter输出以后,lib.js模块内部的变化就影响不到counter了。<strong>这是因为counter是一个原始类型的值,会被缓存。除非写成一个函数,才能得到内部变动后的值</strong>。</p> <h4>(5)服务器端实现</h4> <h4>①下载安装<a href="http://www.js-code.com/tag/node" title="node" target="_blank">node</a>.js</h4> <h4>②创建项目结构</h4> <p><strong>注意:用npm init 自动生成<a href="http://www.js-code.com/tag/package" title="package" target="_blank">package</a>.json时,<a href="http://www.js-code.com/tag/package" title="package" target="_blank">package</a> <a href="http://www.js-code.com/tag/name" title="name" target="_blank">name</a>(包名)不能有中文和大写</strong></p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="|-modules |-module1.js |-module2.js |-module3.js |-app.js |-package.json { &quot;name&quot;: &quot;commonJS-node&quot;, &quot;version&quot;: &quot;1.0.0&quot; }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs ruby"><code><span class="hljs-params">|-modules |</span>-module1.js <span class="hljs-params">|-module2.js |</span>-module3.js <span class="hljs-params">|-app.js |</span>-<a href="http://www.js-code.com/tag/package" title="浏览关于“package”的文章" target="_blank" class="tag_link">package</a>.json { <span class="hljs-string">"<a href="http://www.js-code.com/tag/name" title="浏览关于“name”的文章" target="_blank" class="tag_link">name</a>"</span>: <span class="hljs-string">"commonJS-<a href="http://www.js-code.com/tag/node" title="浏览关于“node”的文章" target="_blank" class="tag_link">node</a>"</span>, <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span> }</code></pre> <h4>③下载第三方模块</h4> <p><code>npm inst<a href="http://www.js-code.com/tag/all" title="all" target="_blank">all</a> uniq --save // 用于<a href="http://www.js-code.com/tag/%e6%95%b0%e7%bb%84" title="数组" target="_blank">数组</a>去重</code></p> <h4>④定义模块代码</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//module1.js module.exports = { msg: 'module1', foo() { console.log(this.msg) } }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">//module1.js</span> <span class="hljs-built_in">module</span>.exports = { msg: <span class="hljs-string">'module1'</span>, foo() { <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.msg) } }</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//module2.js module.exports = function() { console.log('module2') }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">//module2.js</span> <span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'module2'</span>) }</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//module3.js exports.foo = function() { console.log('foo() module3') } exports.arr = [1, 2, 3, 3, 2]" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">//module3.js</span> exports.foo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'foo() module3'</span>) } exports.arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>]</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// app.js文件 // 引入第三方库,应该放置在最前面 let uniq = require('uniq') let module1 = require('./modules/module1') let module2 = require('./modules/module2') let module3 = require('./modules/module3') module1.foo() //module1 module2() //module2 module3.foo() //foo() module3 console.log(uniq(module3.arr)) //[ 1, 2, 3 ]" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// app.js文件</span> <span class="hljs-comment">// 引入第三方库,应该放置在最前面</span> <span class="hljs-keyword">let</span> uniq = <span class="hljs-built_in">require</span>(<span class="hljs-string">'uniq'</span>) <span class="hljs-keyword">let</span> module1 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./modules/module1'</span>) <span class="hljs-keyword">let</span> module2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./modules/module2'</span>) <span class="hljs-keyword">let</span> module3 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./modules/module3'</span>) module1.foo() <span class="hljs-comment">//module1</span> module2() <span class="hljs-comment">//module2</span> module3.foo() <span class="hljs-comment">//foo() module3</span> <span class="hljs-built_in">console</span>.log(uniq(module3.arr)) <span class="hljs-comment">//[ 1, 2, 3 ]</span></code></pre> <h4>⑤通过<a href="http://www.js-code.com/tag/node" title="node" target="_blank">node</a>运行app.js</h4> <p>命令行输入<code>node app.js</code>,运行JS文件</p> <h4>(6)浏览器端实现(借助Browser<a href="http://www.js-code.com/tag/if" title="if" target="_blank">if</a>y)</h4> <h4>①创建项目结构</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="|-js |-dist //打包生成文件的目录 |-src //源码所在的目录 |-module1.js |-module2.js |-module3.js |-app.js //应用主源文件 |-index.html //运行于浏览器上 |-package.json { &quot;name&quot;: &quot;browserify-test&quot;, &quot;version&quot;: &quot;1.0.0&quot; }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs actionscript"><code>|-js |-dist <span class="hljs-comment">//打包生成文件的目录</span> |-src <span class="hljs-comment">//源码所在的目录</span> |-module1.js |-module2.js |-module3.js |-app.js <span class="hljs-comment">//应用主源文件</span> |-index.html <span class="hljs-comment">//运行于浏览器上</span> |-<span class="hljs-class"><span class="hljs-keyword">package</span>.<span class="hljs-title">json</span> {</span> <span class="hljs-string">"name"</span>: <span class="hljs-string">"browser<a href="http://www.js-code.com/tag/if" title="浏览关于“if”的文章" target="_blank" class="tag_link">if</a>y-test"</span>, <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span> }</code></pre> <h4>②下载browser<a href="http://www.js-code.com/tag/if" title="if" target="_blank">if</a>y</h4> <ul> <li>全局: npm inst<a href="http://www.js-code.com/tag/all" title="all" target="_blank">all</a> browserify -g</li> <li>局部: npm inst<a href="http://www.js-code.com/tag/all" title="浏览关于“all”的文章" target="_blank" class="tag_link">all</a> browserify --save-dev</li> </ul> <h4>③定义模块代码(同服务器端)</h4> <p>注意:<code>index.html</code>文件要运行在浏览器上,需要借助browserify将<code>app.js</code>文件打包编译,如果直接在<code>index.html</code>引入<code>app.js</code>就会报错!</p> <h4>④打包处理js</h4> <p>根目录下运行<code>browserify js/src/app.js -o js/dist/bundle.js </code></p> <h4>⑤页面使用引入</h4> <p>在index.html文件中引入<code>&lt;script type="text/<a href="http://www.js-code.com/tag/java" title="java" target="_blank">java</a>script" src="js/dist/bundle.js"&gt;&lt;/script&gt; </code></p> <h3 id="articleHeader8">2.AMD</h3> <p>CommonJS规范加载模块是同步的,也就是说,只有加载完成,才能执行后面的操作。AMD规范则是非同步加载模块,允许指定回调函数。由于Node.js主要用于服务器编程,模块文件一般都已经存在于本地硬盘,所以加载起来比较快,不用考虑非同步加载的方式,所以CommonJS规范比较适用。但是,<strong>如果是浏览器环境,要从服务器端加载模块,这时就必须采用非同步模式,因此浏览器端一般采用AMD规范</strong>。此外AMD规范比CommonJS规范在浏览器端实现要来着早。</p> <h4>(1)AMD规范基本语法</h4> <p><strong>定义暴露模块</strong>:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//定义没有依赖的模块 define(function(){ return 模块 })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs actionscript"><code><span class="hljs-comment">//定义没有依赖的模块</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">()</span></span>{ <span class="hljs-keyword">return</span> 模块 })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//定义有依赖的模块 define(['module1', 'module2'], function(m1, m2){ return 模块 })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs actionscript"><code><span class="hljs-comment">//定义有依赖的模块</span> define([<span class="hljs-string">'module1'</span>, <span class="hljs-string">'module2'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(m1, m2)</span></span>{ <span class="hljs-keyword">return</span> 模块 })</code></pre> <p><strong>引入使用模块</strong>:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="require(['module1', 'module2'], function(m1, m2){ 使用m1/m2 })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs lua"><code><span class="hljs-built_in">require</span>([<span class="hljs-string">'module1'</span>, <span class="hljs-string">'module2'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(m1, m2)</span></span>{ 使用m1/m2 })</code></pre> <h4>(2)未使用AMD规范与使用require.js</h4> <p>通过比较两者的实现方法,来说明使用AMD规范的好处。</p> <ul> <li>未使用AMD规范</li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// dataService.js文件 (function (window) { let msg = 'www.baidu.com' function getMsg() { return msg.toUpperCase() } window.dataService = {getMsg} })(window)" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// dataService.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">window</span>) </span>{ <span class="hljs-keyword">let</span> msg = <span class="hljs-string">'www.baidu.com'</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getMsg</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> msg.toUpperCase() } <span class="hljs-built_in">window</span>.dataService = {getMsg} })(<span class="hljs-built_in">window</span>)</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text=" // alerter.js文件 (function (window, dataService) { let name = 'Tom' function showMsg() { alert(dataService.getMsg() + ', ' + name) } window.alerter = {showMsg} })(window, dataService)" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code> <span class="hljs-comment">// <a href="http://www.js-code.com/tag/alert" title="浏览关于“alert”的文章" target="_blank" class="tag_link">alert</a>er.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">window, dataService</span>) </span>{ <span class="hljs-keyword">let</span> name = <span class="hljs-string">'Tom'</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMsg</span>(<span class="hljs-params"></span>) </span>{ alert(dataService.getMsg() + <span class="hljs-string">', '</span> + name) } <span class="hljs-built_in">window</span>.alerter = {showMsg} })(<span class="hljs-built_in">window</span>, dataService)</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// main.js文件 (function (alerter) { alerter.showMsg() })(alerter)" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs actionscript"><code><span class="hljs-comment">// main.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(alerter)</span> </span>{ alerter.showMsg() })(alerter)</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="浏览关于“button”的文章" target="_blank" class="tag_link">button</a>" class="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="浏览关于“top”的文章" target="_blank" class="tag_link">top</a>" data-clipboard-text="// index.html文件</p> <div> <h1>Modular Demo 1: 未使用AMD(require.js)</h1> </div> <p><script type=&quot;text/javascript&quot; src=&quot;js/modules/dataService.js&quot;></script><br /> <script type=&quot;text/javascript&quot; src=&quot;js/modules/alerter.js&quot;></script><br /> <script type=&quot;text/javascript&quot; src=&quot;js/main.js&quot;></script>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code>// index.html文件 <span class="hljs-tag">&lt;<span class="hljs-name"><a href="http://www.js-code.com/tag/div" title="浏览关于“div”的文章" target="_blank" class="tag_link">div</a></span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Modular Demo 1: 未使用AMD(require.js)<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/modules/dataService.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/modules/alerter.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/main.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre> <p>最后得到如下结果:<br /><span class="img-wrap"><img data-src="/img/remote/1460000017466125?w=508&amp;h=170" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="" title="" style="cursor: pointer;"></span></p> <p>这种方式缺点很明显:<strong>首先会发送多个请求,其次引入的js文件顺序不能搞错,否则会报错!</strong></p> <ul> <li>使用require.js</li> </ul> <p>RequireJS是一个工具库,主要用于客户端的模块管理。它的模块管理遵守AMD规范,<strong>RequireJS的基本思想是,通过define方法,将代码定义为模块;通过require方法,实现代码的模块加载</strong>。<br />接下来介绍AMD规范在浏览器实现的步骤:</p> <h4>①下载require.js, 并引入</h4> <ul> <li>官网: <code>http://www.requirejs.cn/</code> </li> <li>github : <code>https://github.com/requirejs/requirejs</code> </li> </ul> <p>然后将require.js导入项目: js/libs/require.js</p> <h4>②创建项目结构</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="|-js |-libs |-require.js |-modules |-alerter.js |-dataService.js |-main.js |-index.html" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs ruby"><code><span class="hljs-params">|-js |</span>-libs <span class="hljs-params">|-<span class="hljs-keyword">require</span>.js |</span>-modules <span class="hljs-params">|-alerter.js |</span>-dataService.js <span class="hljs-params">|-main.js |</span>-index.html</code></pre> <h4>③定义require.js的模块代码</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// dataService.js文件 // 定义没有依赖的模块 define(function() { let msg = 'www.baidu.com' function getMsg() { return msg.toUpperCase() } return { getMsg } // 暴露模块 })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// dataService.js文件 </span> <span class="hljs-comment">// 定义没有依赖的模块</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">let</span> msg = <span class="hljs-string">'www.baidu.com'</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getMsg</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> msg.toUpperCase() } <span class="hljs-keyword">return</span> { getMsg } <span class="hljs-comment">// 暴露模块</span> })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//alerter.js文件 // 定义有依赖的模块 define(['dataService'], function(dataService) { let name = 'Tom' function showMsg() { alert(dataService.getMsg() + ', ' + name) } // 暴露模块 return { showMsg } })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">//alerter.js文件</span> <span class="hljs-comment">// 定义有依赖的模块</span> define([<span class="hljs-string">'dataService'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">dataService</span>) </span>{ <span class="hljs-keyword">let</span> name = <span class="hljs-string">'Tom'</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMsg</span>(<span class="hljs-params"></span>) </span>{ alert(dataService.getMsg() + <span class="hljs-string">', '</span> + name) } <span class="hljs-comment">// 暴露模块</span> <span class="hljs-keyword">return</span> { showMsg } })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// main.js文件 (function() { require.config({ baseUrl: 'js/', //基本路径 出发点在根目录下 paths: { //映射: 模块标识名: 路径 alerter: './modules/alerter', //此处不能写成alerter.js,会报错 dataService: './modules/dataService' } }) require(['alerter'], function(alerter) { alerter.showMsg() }) })()" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// main.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">require</span>.config({ <span class="hljs-attr">baseUrl</span>: <span class="hljs-string">'js/'</span>, <span class="hljs-comment">//基本路径 出发点在根目录下</span> paths: { <span class="hljs-comment">//映射: 模块标识名: 路径</span> alerter: <span class="hljs-string">'./modules/alerter'</span>, <span class="hljs-comment">//此处不能写成alerter.js,会报错</span> dataService: <span class="hljs-string">'./modules/dataService'</span> } }) <span class="hljs-built_in">require</span>([<span class="hljs-string">'alerter'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">alerter</span>) </span>{ alerter.showMsg() }) })()</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// index.html文件 <!DOCTYPE html><br /> <html><br /> <head><br /> <title>Modular Demo</title><br /> </head><br /> <body><br /> <!-- 引入require.js并指定js主文件的入口 --><br /> <script data-main=&quot;js/main&quot; src=&quot;js/libs/require.js&quot;></script><br /> </body><br /> </html>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code>// index.html文件 <span class="hljs-meta">&lt;!DOCTYPE html&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Modular Demo<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span> <span class="hljs-comment">&lt;!-- 引入require.js并指定js主文件的入口 --&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">data-main</span>=<span class="hljs-string">"js/main"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/libs/require.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre> <h4>④页面引入require.js模块:</h4> <p>在index.html引入 <code>&lt;script data-main="js/main" src="js/libs/require.js"&gt;&lt;/script&gt; </code></p> <p><strong>此外在项目中如何引入第三方库?</strong>只需在上面代码的基础稍作修改:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// alerter.js文件 define(['dataService', 'jquery'], function(dataService, $) { let name = 'Tom' function showMsg() { alert(dataService.getMsg() + ', ' + name) } $('body').css('background', 'green') // 暴露模块 return { showMsg } })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// alerter.js文件</span> define([<span class="hljs-string">'dataService'</span>, <span class="hljs-string">'jquery'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">dataService, $</span>) </span>{ <span class="hljs-keyword">let</span> name = <span class="hljs-string">'Tom'</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMsg</span>(<span class="hljs-params"></span>) </span>{ alert(dataService.getMsg() + <span class="hljs-string">', '</span> + name) } $(<span class="hljs-string">'body'</span>).css(<span class="hljs-string">'background'</span>, <span class="hljs-string">'green'</span>) <span class="hljs-comment">// 暴露模块</span> <span class="hljs-keyword">return</span> { showMsg } })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// main.js文件 (function() { require.config({ baseUrl: 'js/', //基本路径 出发点在根目录下 paths: { //自定义模块 alerter: './modules/alerter', //此处不能写成alerter.js,会报错 dataService: './modules/dataService', // 第三方库模块 jquery: './libs/jquery-1.10.1' //注意:写成jQuery会报错 } }) require(['alerter'], function(alerter) { alerter.showMsg() }) })()" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// main.js文件</span> (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">require</span>.config({ <span class="hljs-attr">baseUrl</span>: <span class="hljs-string">'js/'</span>, <span class="hljs-comment">//基本路径 出发点在根目录下</span> paths: { <span class="hljs-comment">//自定义模块</span> alerter: <span class="hljs-string">'./modules/alerter'</span>, <span class="hljs-comment">//此处不能写成alerter.js,会报错</span> dataService: <span class="hljs-string">'./modules/dataService'</span>, <span class="hljs-comment">// 第三方库模块</span> jquery: <span class="hljs-string">'./libs/jquery-1.10.1'</span> <span class="hljs-comment">//注意:写成jQuery会报错</span> } }) <span class="hljs-built_in">require</span>([<span class="hljs-string">'alerter'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">alerter</span>) </span>{ alerter.showMsg() }) })()</code></pre> <p>上例是在<a href="http://www.js-code.com/tag/alert" title="alert" target="_blank">alert</a>er.js文件中引入jQuery第三方库,main.js文件也要有相应的路径配置。<br /><strong>小结</strong>:通过两者的比较,可以得出<strong>AMD模块定义的方法非常清晰,不会污染全局环境,能够清楚地显示依赖关系</strong>。AMD模式可以用于浏览器环境,并且允许非同步加载模块,也可以根据需要动态加载模块。</p> <h3 id="articleHeader9">3.CMD</h3> <p>CMD规范专门用于浏览器端,模块的加载是异步的,模块使用时才会加载执行。CMD规范整合了CommonJS和AMD规范的特点。在 Sea.js 中,所有 JavaScript 模块都遵循 CMD模块定义规范。</p> <h4>(1)CMD规范基本语法</h4> <p><strong>定义暴露模块:</strong></p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//定义没有依赖的模块 define(function(require, exports, module){ exports.xxx = value module.exports = value })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">//定义没有依赖的模块</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">require</span>, exports, <span class="hljs-built_in">module</span></span>)</span>{ exports.xxx = value <span class="hljs-built_in">module</span>.exports = value })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//定义有依赖的模块 define(function(require, exports, module){ //引入依赖模块(同步) var module2 = require('./module2') //引入依赖模块(异步) require.async('./module3', function (m3) { }) //暴露模块 exports.xxx = value })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">//定义有依赖的模块</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">require</span>, exports, <span class="hljs-built_in">module</span></span>)</span>{ <span class="hljs-comment">//引入依赖模块(同步)</span> <span class="hljs-keyword">var</span> module2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./module2'</span>) <span class="hljs-comment">//引入依赖模块(异步)</span> <span class="hljs-built_in">require</span>.async(<span class="hljs-string">'./module3'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">m3</span>) </span>{ }) <span class="hljs-comment">//暴露模块</span> exports.xxx = value })</code></pre> <p><strong>引入使用模块:</strong></p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="define(function (require) { var m1 = require('./module1') var m4 = require('./module4') m1.show() m4.show() })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code>define(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-built_in">require</span></span>) </span>{ <span class="hljs-keyword">var</span> m1 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./module1'</span>) <span class="hljs-keyword">var</span> m4 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./module4'</span>) m1.show() m4.show() })</code></pre> <h4>(2)sea.js简单使用教程</h4> <h4>①下载sea.js, 并引入</h4> <ul> <li>官网: <a href="http://seajs.org/" rel="nofollow noreferrer" target="_blank">http://seajs.org/</a> </li> <li>github : <a href="https://github.com/seajs/seajs" rel="nofollow noreferrer" target="_blank">https://github.com/seajs/seajs</a> </li> </ul> <p>然后将sea.js导入项目: js/libs/sea.js</p> <h4>②创建项目结构</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="|-js |-libs |-sea.js |-modules |-module1.js |-module2.js |-module3.js |-module4.js |-main.js |-index.html" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs ruby"><code><span class="hljs-params">|-js |</span>-libs <span class="hljs-params">|-sea.js |</span>-modules <span class="hljs-params">|-module1.js |</span>-module2.js <span class="hljs-params">|-module3.js |</span>-module4.js <span class="hljs-params">|-main.js |</span>-index.html</code></pre> <h4>③定义sea.js的模块代码</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// module1.js文件 define(function (require, exports, module) { //内部变量数据 var data = 'atguigu.com' //内部函数 function show() { console.log('module1 show() ' + data) } //向外暴露 exports.show = show })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// module1.js文件</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-built_in">require</span>, exports, <span class="hljs-built_in">module</span></span>) </span>{ <span class="hljs-comment">//内部变量数据</span> <span class="hljs-keyword">var</span> data = <span class="hljs-string">'atguigu.com'</span> <span class="hljs-comment">//内部函数</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'module1 show() '</span> + data) } <span class="hljs-comment">//向外暴露</span> exports.show = show })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// module2.js文件 define(function (require, exports, module) { module.exports = { msg: 'I Will Back' } })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// module2.js文件</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-built_in">require</span>, exports, <span class="hljs-built_in">module</span></span>) </span>{ <span class="hljs-built_in">module</span>.exports = { msg: <span class="hljs-string">'I Will Back'</span> } })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// module3.js文件 define(function(require, exports, module) { const API_KEY = 'abc123' exports.API_KEY = API_KEY })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// module3.js文件</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">require</span>, exports, <span class="hljs-built_in">module</span></span>) </span>{ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> <a href="http://www.js-code.com/tag/api" title="浏览关于“API”的文章" target="_blank" class="tag_link">API</a>_KEY = <span class="hljs-string">'abc123'</span> exports.API_KEY = API_KEY })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// module4.js文件 define(function (require, exports, module) { //引入依赖模块(同步) var module2 = require('./module2') function show() { console.log('module4 show() ' + module2.msg) } exports.show = show //引入依赖模块(异步) require.async('./module3', function (m3) { console.log('异步引入依赖模块3 ' + m3.API_KEY) }) })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// module4.js文件</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">require, exports, module</span>) </span>{ <span class="hljs-comment">//引入依赖模块(同步)</span> <span class="hljs-keyword">var</span> module2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./module2'</span>) <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'module4 show() '</span> + module2.msg) } exports.show = show <span class="hljs-comment">//引入依赖模块(异步)</span> <span class="hljs-built_in">require</span>.async(<span class="hljs-string">'./module3'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">m3</span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'异步引入依赖模块3 '</span> + m3.API_KEY) }) })</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// main.js文件 define(function (require) { var m1 = require('./module1') var m4 = require('./module4') m1.show() m4.show() })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// main.js文件</span> define(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-built_in">require</span></span>) </span>{ <span class="hljs-keyword">var</span> m1 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./module1'</span>) <span class="hljs-keyword">var</span> m4 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./module4'</span>) m1.show() m4.show() })</code></pre> <h4>④在index.html中引入</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="<script type=&quot;text/javascript&quot; src=&quot;js/libs/sea.js&quot;></script><br /> <script type=&quot;text/javascript&quot;> seajs.use('./js/modules/main') </script>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/libs/sea.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="actionscript"> seajs.use(<span class="hljs-string">'./js/modules/main'</span>) </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre> <p>最后得到结果如下:</p> <p><span class="img-wrap"><img data-src="/img/remote/1460000017466126?w=430&amp;h=84" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="" title="" style="cursor: pointer;"></span></p> <h3 id="articleHeader10">4.<a href="http://www.js-code.com/tag/es6%e6%a8%a1%e5%9d%97" title="ES6模块" target="_blank">ES6模块</a>化</h3> <p>ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。CommonJS 和 AMD 模块,都只能在运行时确定这些东西。比如,CommonJS 模块就是对象,输入时必须查找对象属性。</p> <h4>(1)<a href="http://www.js-code.com/tag/es6%e6%a8%a1%e5%9d%97" title="浏览关于“ES6模块”的文章" target="_blank" class="tag_link">ES6模块</a>化语法</h4> <p>export命令用于规定模块的对外接口,<a href="http://www.js-code.com/tag/import" title="import" target="_blank">import</a>命令用于输入其他模块提供的功能。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="/** 定义模块 math.js **/ var basicNum = 0; var add = function (a, b) { return a + b; }; export { basicNum, add }; /** 引用模块 **/ import { basicNum, add } from './math'; function test(ele) { ele.textContent = add(99 + basicNum); }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">/** 定义模块 math.js **/</span> <span class="hljs-keyword">var</span> basicNum = <span class="hljs-number">0</span>; <span class="hljs-keyword">var</span> add = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{ <span class="hljs-keyword">return</span> a + b; }; <span class="hljs-keyword">export</span> { basicNum, add }; <span class="hljs-comment">/** 引用模块 **/</span> <span class="hljs-keyword">import</span> { basicNum, add } <span class="hljs-keyword">from</span> <span class="hljs-string">'./math'</span>; <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params">ele</span>) </span>{ ele.textContent = add(<span class="hljs-number">99</span> + basicNum); }</code></pre> <p>如上例所示,使用<a href="http://www.js-code.com/tag/import" title="import" target="_blank">import</a>命令的时候,用户需要知道所要加载的变量名或函数名,否则无法加载。为了给用户提供方便,让他们不用阅读文档就能加载模块,就要用到export <a href="http://www.js-code.com/tag/default" title="default" target="_blank">default</a>命令,为模块指定默认输出。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// export-default.js export default function () { console.log('foo'); }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// export-<a href="http://www.js-code.com/tag/default" title="浏览关于“default”的文章" target="_blank" class="tag_link">default</a>.js</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'foo'</span>); }</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// import-default.js import customName from './export-default'; customName(); // 'foo'" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs coffeescript"><code><span class="hljs-regexp">//</span> <span class="hljs-keyword">import</span>-<span class="hljs-keyword">default</span>.js <span class="hljs-keyword">import</span> customName <span class="hljs-keyword">from</span> <span class="hljs-string">'./export-default'</span>; customName(); <span class="hljs-regexp">//</span> <span class="hljs-string">'foo'</span></code></pre> <p>模块默认输出, 其他模块加载该模块时,import命令可以为该匿名函数指定任意名字。</p> <h4>(2)ES6 模块与 CommonJS 模块的差异</h4> <p>它们有两个重大差异:</p> <p><strong>① CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用</strong>。</p> <p><strong>② CommonJS 模块是运行时加载,ES6 模块是编译时输出接口</strong>。</p> <p>第二个差异是因为 CommonJS 加载的是一个对象(即module.exports属性),该对象只有在脚本运行完才会生成。而 ES6 模块不是对象,它的对外接口只是一种静态定义,在代码静态解析阶段就会生成。</p> <p>下面重点解释第一个差异,我们还是举上面那个CommonJS模块的加载机制例子:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// lib.js export let counter = 3; export function incCounter() { counter++; } // main.js import { counter, incCounter } from './lib'; console.log(counter); // 3 incCounter(); console.log(counter); // 4" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// lib.js</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> counter = <span class="hljs-number">3</span>; <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">incCounter</span>(<span class="hljs-params"></span>) </span>{ counter++; } <span class="hljs-comment">// main.js</span> <span class="hljs-keyword">import</span> { counter, incCounter } <span class="hljs-keyword">from</span> <span class="hljs-string">'./lib'</span>; <span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 3</span> incCounter(); <span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 4</span></code></pre> <p>ES6 模块的运行机制与 CommonJS 不一样。<strong>ES6 模块是动态引用,并且不会缓存值,模块里面的变量绑定其所在的模块</strong>。</p> <h4>(3) ES6-Babel-Browserify使用教程</h4> <p>简单来说就一句话:<strong>使用Babel将ES6编译为ES5代码,使用Browserify编译打包js</strong>。</p> <h4>①定义package.json文件</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text=" { &quot;name&quot; : &quot;es6-babel-browserify&quot;, &quot;version&quot; : &quot;1.0.0&quot; }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs json"><code> { <span class="hljs-attr">"name"</span> : <span class="hljs-string">"<a href="http://www.js-code.com/tag/es6" title="浏览关于“es6”的文章" target="_blank" class="tag_link">es6</a>-<a href="http://www.js-code.com/tag/babel" title="浏览关于“babel”的文章" target="_blank" class="tag_link">babel</a>-browserify"</span>, <span class="hljs-attr">"version"</span> : <span class="hljs-string">"1.0.0"</span> }</code></pre> <h4>②安装<a href="http://www.js-code.com/tag/babel" title="babel" target="_blank">babel</a>-cli, <a href="http://www.js-code.com/tag/babel" title="babel" target="_blank">babel</a>-p<a href="http://www.js-code.com/tag/reset" title="reset" target="_blank">reset</a>-es2015和browserify</h4> <li> <ul> <li>npm install babel-cli browserify -g</li> </ul> </li> <ul> <li>npm install babel-p<a href="http://www.js-code.com/tag/reset" title="reset" target="_blank">reset</a>-es2015 --save-dev</li> <li>p<a href="http://www.js-code.com/tag/reset" title="浏览关于“reset”的文章" target="_blank" class="tag_link">reset</a> 预设(将<a href="http://www.js-code.com/tag/es6" title="es6" target="_blank">es6</a>转换成<a href="http://www.js-code.com/tag/es5" title="es5" target="_blank">es5</a>的所有插件打包)</li> </ul> <h4>③定义.babelrc文件</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text=" { &quot;presets&quot;: [&quot;es2015&quot;] }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs json"><code> { <span class="hljs-attr">"presets"</span>: [<span class="hljs-string">"es2015"</span>] }</code></pre> <h4>④定义模块代码</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//module1.js文件 // 分别暴露 export function foo() { console.log('foo() module1') } export function bar() { console.log('bar() module1') }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">//module1.js文件</span> <span class="hljs-comment">// 分别暴露</span> <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'foo() module1'</span>) } <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'bar() module1'</span>) }</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//module2.js文件 // 统一暴露 function fun1() { console.log('fun1() module2') } function fun2() { console.log('fun2() module2') } export { fun1, fun2 }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">//module2.js文件</span> <span class="hljs-comment">// 统一暴露</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fun1() module2'</span>) } <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun2</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fun2() module2'</span>) } <span class="hljs-keyword">export</span> { fun1, fun2 }</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//module3.js文件 // 默认暴露 可以暴露任意数据类项,暴露什么数据,接收到就是什么数据 export default () => {<br /> console.log('默认暴露')<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">//module3.js文件</span> <span class="hljs-comment">// 默认暴露 可以暴露任意数据类项,暴露什么数据,接收到就是什么数据</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'默认暴露'</span>) }</code></pre> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// app.js文件 import { foo, bar } from './module1' import { fun1, fun2 } from './module2' import module3 from './module3' foo() bar() fun1() fun2() module3()" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// app.js文件</span> <span class="hljs-keyword">import</span> { foo, bar } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module1'</span> <span class="hljs-keyword">import</span> { fun1, fun2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module2'</span> <span class="hljs-keyword">import</span> module3 <span class="hljs-keyword">from</span> <span class="hljs-string">'./module3'</span> foo() bar() fun1() fun2() module3()</code></pre> <h4>⑤ 编译并在index.html中引入</h4> <ul> <li>使用Babel将ES6编译为ES5代码(但包含CommonJS语法) : <code>babel js/src -d js/lib</code> </li> <li>使用Browserify编译js : <code>browserify js/lib/app.js -o js/lib/bundle.js</code> </li> </ul> <p>然后在index.html文件中引入</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text=" <script type=&quot;text/javascript&quot; src=&quot;js/lib/bundle.js&quot;></script>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code style="word-break: break-word; white-space: initial;"> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/lib/bundle.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre> <p>最后得到如下结果:</p> <p><span class="img-wrap"><img data-src="/img/remote/1460000017466127?w=437&amp;h=102" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="" title="" style="cursor: pointer;"></span></p> <p><strong>此外第三方库(以jQuery为例)如何引入呢</strong>?<br />首先安装依赖<code>npm install jquery@1</code><br />然后在app.js文件中引入</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//app.js文件 import { foo, bar } from './module1' import { fun1, fun2 } from './module2' import module3 from './module3' import $ from 'jquery' foo() bar() fun1() fun2() module3() $('body').css('background', 'green')" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">//app.js文件</span> <span class="hljs-keyword">import</span> { foo, bar } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module1'</span> <span class="hljs-keyword">import</span> { fun1, fun2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module2'</span> <span class="hljs-keyword">import</span> module3 <span class="hljs-keyword">from</span> <span class="hljs-string">'./module3'</span> <span class="hljs-keyword">import</span> $ <span class="hljs-keyword">from</span> <span class="hljs-string">'jquery'</span> foo() bar() fun1() fun2() module3() $(<span class="hljs-string">'body'</span>).css(<span class="hljs-string">'background'</span>, <span class="hljs-string">'green'</span>)</code></pre> <h2 id="articleHeader11">三、总结</h2> <ul> <li>CommonJS规范主要用于服务端编程,加载模块是同步的,这并不适合在浏览器环境,因为同步意味着阻塞加载,浏览器资源是异步加载的,因此有了AMD CMD解决方案。</li> <li>AMD规范在浏览器环境中异步加载模块,而且可以并行加载多个模块。不过,AMD规范开发成本高,代码的阅读和书写比较困难,模块定义方式的语义不顺畅。</li> <li>CMD规范与AMD规范很相似,都用于浏览器编程,依赖就近,延迟执行,可以很容易在Node.js中运行。不过,依赖SPM 打包,模块的加载逻辑偏重</li> <li> <strong>ES6 在语言标准的层面上,实现了模块功能,而且实现得相当简单,完全可以取代 CommonJS 和 AMD 规范,成为浏览器和服务器通用的模块解决方案</strong>。</li> </ul> <h2 id="articleHeader12">后记</h2> <p>花了很长时间(&gt;10h)终于把"JS模块化"讲清楚,自己对模块化的认识又加深了一步,事实上,理解一件事并不难,难的是如何将一件事通俗分享给别人,并让别人也有所收获,一直以来我也是这样要求自己!文章如有错误和不正之处,欢迎指正和批评,同时也希望大家多多支持,我会有更大的创作动力!</p> <p><span class="img-wrap"><img data-src="/img/remote/1460000017466128?w=347&amp;h=205" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="" title="" style="cursor: pointer;"></span></p> <h2 id="articleHeader13">参考文章</h2> <h3 id="articleHeader14"><a href="https://github.com/seajs/seajs/issues/588" rel="nofollow noreferrer" target="_blank">前端模块化开发那点历史</a></h3> <h3 id="articleHeader15"><a href="https://zccst.iteye.com/blog/2215317" rel="nofollow noreferrer" target="_blank">CommonJS,AMD,CMD区别</a></h3> <h3 id="articleHeader16"><a href="https://www.zhihu.com/question/20351507/answer/14859415" rel="nofollow noreferrer" target="_blank">AMD 和 CMD 的区别有哪些?</a></h3> <h3 id="articleHeader17"><a href="http://www.ruanyifeng.com/blog/2012/10/javascript_module.html" rel="nofollow noreferrer" target="_blank">Javascript模块化编程</a></h3> <h3 id="articleHeader18"><a href="http://javascript.ruanyifeng.com/nodejs/module.html" rel="nofollow noreferrer" target="_blank">Javascript标准参考教程</a></h3> <h3 id="articleHeader19"><a href="https://github.com/seajs/seajs/issues/242" rel="nofollow noreferrer" target="_blank">CMD 模块定义规范</a></h3> <h3 id="articleHeader20"><a href="https://zhuanlan.zhihu.com/p/26625636" rel="nofollow noreferrer" target="_blank">理解CommonJS、AMD、CMD三种规范</a></h3> <p></code></p>

总结

以上是脚本宝典为你收集整理的

前端模块化详解(完整版)

全部内容,希望文章能够帮你解决

前端模块化详解(完整版)

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过