A place to cache linked articles (think custom and personal wayback machine)
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

4 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. title: The mind-boggling universe of JavaScript Module strategies
  2. url: https://www.airpair.com/javascript/posts/the-mind-boggling-universe-of-javascript-modules
  3. hash_url: 85169542c2bb95c8424a3081ec0b90b1
  4. <p>If you feel like, no matter what you do, there is always something funky in your JavaScript code, I would bet that your Module strategy is not working out so well.</p>
  5. <p>The importance of adopting a proper JavaScript Module strategy is often underestimated as a preference contest, so it is important to truly understand your needs. This article exposes the foundations of different JavaScript Module strategies such as ad hoc, CommonJS, AMD and ES6 modules, and how to get started with ES6 modules right now.</p>
  6. <h2 id="javascript-module-101">JavaScript Module 101</h2>
  7. <p>In brief terms, JavaScript Modules were created in order to apply some classic Object Orientation ideas when building components, once the current JavaScript language support for those ideas isn't as explicit as in other languages as C++, Java and Ruby.</p>
  8. <p>In order to build a module as a special type of object, which strongly needs to leverage encapsulation, we need to add support for declaring private/public attributes and methods inside a single object. Enter the <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript">Module pattern</a>, where such encapsulation is achieved through <strong>function closures</strong>, taking advantage of the <strong>function scope</strong> to publicly disclose only what is necessary through the return of the function. </p>
  9. <p>Look at the following example for an ad hoc module implementation:</p>
  10. <p><strong>zoo.js:</strong></p>
  11. <pre><code class="lang-javascript">var Zoo = (function() {
  12. var getBarkStyle = function(isHowler) {
  13. return isHowler? 'woooooow!': 'woof, woof!';
  14. };
  15. var Dog = function(name, breed) {
  16. this.bark = function() {
  17. return name + ': ' + getBarkStyle(breed === 'husky');
  18. };
  19. };
  20. var Wolf = function(name) {
  21. this.bark = function() {
  22. return name + ': ' + getBarkStyle(true);
  23. };
  24. };
  25. return {
  26. Dog: Dog,
  27. Wolf: Wolf
  28. };
  29. })();
  30. </code></pre>
  31. <p>In <code>zoo.js</code>, we have built the module <code>Zoo</code> which only publicly exposes the functions <code>Dog</code> and <code>Wolf</code>, keeping the function <code>getBarkStyle</code> as private to the module. Precisely, this implementation is a module variation known as the <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript">Revealing Module pattern</a>.</p>
  32. <p>Now, let's see how to consume this module:</p>
  33. <p><strong>main.js:</strong> </p>
  34. <pre><code class="lang-javascript">var myDog = new Zoo.Dog('Sherlock', 'beagle');
  35. console.log(myDog.bark()); // Sherlock: woof, woof!
  36. var myWolf = new Zoo.Wolf('Werewolf');
  37. console.log(myWolf.bark()); // Werewolf: woooooow!
  38. </code></pre>
  39. <p>In <code>main.js</code>, we are reading the global variable <code>Zoo</code> and instantiating <code>Dog</code> and <code>Wolf</code> from it. Note here that <code>Zoo</code> is also serving as a namespace for its functions, which is encouraged over root-level functions in order to avoid conflicts with other modules defining functions with similar names. </p>
  40. <p>I have put together a full <a href="http://tiagorg.com/js-modules/ad-hoc/index.html">live example of the ad-hoc module</a>. You can also <a href="https://github.com/tiagorg/js-modules/tree/gh-pages/ad-hoc">check the source code</a>.</p>
  41. <h2 id="ok-modules-are-cool-but-why-should-i-use-them-">Ok, modules are cool, but why should I use them?</h2>
  42. <p>Just to name a few reasons why every JavaScript developer should use modules as much as possible:</p>
  43. <ul>
  44. <li>Writing scattered global JavaScript code is bad for performance, terrible for reusability, causes awkward readability, is painful for side-effects, and horrible for code organization.</li>
  45. <li>In JavaScript, literal objects' attributes and methods are all public, making it impossible to conceal internal details of objects, which is a real demand for Components, Features, Subsystems and Façades.</li>
  46. <li>A module can be delivered as a dependency for other modules, leveraging a composite architecture of reusable components, when properly implemented.</li>
  47. <li>Modules can also be packaged and deployed separately from each other, allowing changes on a particular module to be properly isolated from everything else, therefore mitigating those dreaded side-effects known as the "butterfly effect" (yes, just like the movie).</li>
  48. <li>Splitting your global code into modules is the first step on bringing cohesion up and coupling down.</li>
  49. </ul>
  50. <h2 id="to-be-or-not-to-be-commonjs-or-amd-">To be or not to be, CommonJS or AMD?</h2>
  51. <p>Have another look on the ad hoc module example above. Since we are defining 2 files, we are still writing and reading the variable <code>Zoo</code> into the global JavaScript context. This is definitely not recommended, because it is:</p>
  52. <ul>
  53. <li>fragile (as it is possible for any posterior code to modify/redefine your module),</li>
  54. <li>not scalable (if you need to define 100 modules, all of them will be loaded on the global JavaScript context, even if you end up consuming just 1 out of those 100 modules, making it really bad for performance),</li>
  55. <li>counter-productive (you have to manually resolve your dependencies, and you would need to remember to bring them altogether if you were to use your module in another application).</li>
  56. </ul>
  57. <p>A good solution for such setbacks is adopting a Module Loader. As a matter of fact, it would be entirely possible for you to write your own module loader! A simple homemade loader would just need to register modules under aliases, resolve dependencies through Dependency Injection and instantiate the modules through a Factory.</p>
  58. <p>Over the course of time, many developers started to elaborate around modules and module loaders, striving for defining a multi-purpose Module Standard. After some coming and going, two module standards have gained some momentum:</p>
  59. <h3 id="1-commonjs">1) CommonJS</h3>
  60. <p><a href="http://www.commonjs.org/"><strong>CommonJS</strong></a> is a standard for <strong>synchronous</strong> modules.</p>
  61. <p><strong>Pros:</strong></p>
  62. <ul>
  63. <li>It was adopted as the official module format for <a href="https://nodejs.org">Node.js</a> and <a href="http://npmjs.com">NPM</a> components. This means that any module defined in CommonJS will have access to the whole NPM ecosystem.</li>
  64. <li>It has a simple and convenient syntax.</li>
  65. <li>It is possible to guarantee the order of execution of modules.</li>
  66. </ul>
  67. <p><strong>Cons:</strong></p>
  68. <ul>
  69. <li>It doesn't naturally work on the browser, however there are great solutions for this constraint as <a href="http://browserify.org">Browserify</a> and <a href="http://webpack.github.io">Webpack</a>.</li>
  70. <li>Since it is synchronous, the modules have to be loaded sequentially, which might take more time than if they were to be loaded asynchronously.</li>
  71. <li>Usually, NPM modules are composed by many other modules, which means that you might end up depending on a high number of modules, and your bundles can easily get big.</li>
  72. </ul>
  73. <p><strong>When to use:</strong> CommonJS is already a mature standard for the server-side, and a good option for the client-side when the Javascript bundles executed during the page load time are not too big.</p>
  74. <p><strong>How to use:</strong> Your module file will publicly expose whatever is assigned to <code>module.exports</code> while everything else is private. In order to use your module, the client code needs to use the <code>require(dependency)</code> function, referencing your module per file location or alias.</p>
  75. <p>Check out the following example:</p>
  76. <p><strong>zoo.js:</strong></p>
  77. <pre><code class="lang-javascript">var getBarkStyle = function(isHowler) {
  78. return isHowler? 'woooooow!': 'woof, woof!';
  79. };
  80. var Dog = function(name, breed) {
  81. this.bark = function() {
  82. return name + ': ' + getBarkStyle(breed === 'husky');
  83. };
  84. };
  85. var Wolf = function(name) {
  86. this.bark = function() {
  87. return name + ': ' + getBarkStyle(true);
  88. };
  89. };
  90. module.exports = {
  91. Dog: Dog,
  92. Wolf: Wolf
  93. };
  94. </code></pre>
  95. <p>Note that the public content is returned at once through <code>module.exports</code>.</p>
  96. <p><strong>main.js:</strong></p>
  97. <pre><code class="lang-javascript">var Zoo = require('./zoo');
  98. var myDog = new Zoo.Dog('Sherlock', 'beagle');
  99. console.log(myDog.bark()); // Sherlock: woof, woof!
  100. var myWolf = new Zoo.Wolf('Werewolf');
  101. console.log(myWolf.bark()); // Werewolf: woooooow!
  102. </code></pre>
  103. <p>This code is also available as a <a href="http://tiagorg.com/js-modules/commonjs/index.html">live example of a Common.js module</a>. Make sure to <a href="https://github.com/tiagorg/js-modules/tree/gh-pages/commonjs">check the source code</a>. In this example I am using Browserify to transform the source code on a browser bundle.</p>
  104. <h3 id="2-amd">2) AMD</h3>
  105. <p><a href="https://github.com/amdjs/amdjs-api"><strong>AMD</strong></a> (Asynchronous Module Definition) is a standard for <strong>asynchronous</strong> modules.</p>
  106. <p><strong>Pros:</strong></p>
  107. <ul>
  108. <li>Multiple modules can be loaded in parallel.</li>
  109. <li>It naturally works on the browser.</li>
  110. <li>It is very convenient to defer the loading of modules that are not necessary on page load.</li>
  111. </ul>
  112. <p><strong>Cons:</strong></p>
  113. <ul>
  114. <li>Asynchronous loading is a complex subject and it can easily create race conditions if not properly designed.</li>
  115. <li>It isn't possible to guarantee the order of execution of asynchronous modules.</li>
  116. <li>Its syntax can get hard to understand, specially when the dependencies array is large.</li>
  117. </ul>
  118. <p><strong>When to use:</strong> AMD is specially interesting for client-side applications that can benefit from the lazy loading of modules, when this can be properly leveraged.</p>
  119. <p><strong>How to use:</strong> Your module will publicly expose whatever is being returned on the callback function, similarly to our first ad hoc example. In order to use your module, the client code needs to refer to it (per file location or alias) on its dependencies array, which will map to an argument on its own callback function.</p>
  120. <p>The following example uses the quintessential AMD implementation, <a href="http://requirejs.org">Require.js</a>, where it declares the <code>zoo</code> module using <code>define(alias, dependenciesArray, callbackFunction)</code> and consumes it later using <code>require(dependenciesArray, callbackFunction)</code>:</p>
  121. <p><strong>zoo.js:</strong></p>
  122. <pre><code class="lang-javascript">define('zoo', [], function() {
  123. var getBarkStyle = function (isHowler) {
  124. return isHowler? 'woooooow!': 'woof, woof!';
  125. };
  126. var Dog = function (name, breed) {
  127. this.bark = function() {
  128. return name + ': ' + getBarkStyle(breed === 'husky');
  129. };
  130. };
  131. var Wolf = function (name) {
  132. this.bark = function() {
  133. return name + ': ' + getBarkStyle(true);
  134. };
  135. };
  136. return {
  137. Dog: Dog,
  138. Wolf: Wolf
  139. };
  140. });
  141. </code></pre>
  142. <p>Note that the public content is returned at once through the function return, just like the ad hoc implementation.</p>
  143. <p><strong>main.js:</strong></p>
  144. <pre><code class="lang-javascript">require(['zoo'], function(Zoo) {
  145. var myDog = new Zoo.Dog('Sherlock', 'beagle');
  146. console.log(myDog.bark()); // Sherlock: woof, woof!
  147. var myWolf = new Zoo.Wolf('Werewolf');
  148. console.log(myWolf.bark()); // Werewolf: woooooow!
  149. });
  150. </code></pre>
  151. <p>This code is also available as a <a href="http://tiagorg.com/js-modules/amd/index.html">live example of an AMD module</a>. Make sure to <a href="https://github.com/tiagorg/js-modules/tree/gh-pages/amd">check the source code</a>.</p>
  152. <h3 id="is-there-any-interop-">Is there any interop?</h3>
  153. <p>As you might guess, you will run into both standards quite frequently, and there will be times you might want to use a CommonJS module with an AMD component and vice-versa. Please allow me to spoil your surprise: these standards are not naturally compatible!</p>
  154. <p>Nevertheless, a number of approaches are there to provide more compatibility between CommonJS and AMD, striving to come up with a way to write your module just once and have it working on both standards. Great interop examples are <a href="https://github.com/umdjs/umd">UMD</a>, <a href="https://github.com/systemjs/systemjs">SystemJS</a> and <a href="http://urequire.org">uRequire</a>.</p>
  155. <p>AMD aficionados might also consider <a href="https://github.com/jrburke/almond">Almond</a>, a nifty lightweight AMD implementation which natively supports both synchronous and asynchronous loading. It is not really interop, however it is a single solution that benefits from both worlds.</p>
  156. <h2 id="now-forget-about-that-es6-is-right-around-the-corner-">Now, forget about that. ES6 is right around the corner!</h2>
  157. <p>Earlier I've affirmed that the JavaScript language support for Modules isn't much explicit on its current version (officially known as ECMAScript 5 or just ES5). However, it turns out that JavaScript Modules <strong>have just become explicit</strong>!</p>
  158. <p>The upcoming version of JavaScript (ECMAScript 6 or ES6) offers native support for modules in a compact and effective way, quite a bit similar to CommonJS. See how it will look like:</p>
  159. <p><strong>zoo.js:</strong> </p>
  160. <pre><code class="lang-javascript">var getBarkStyle = function(isHowler) {
  161. return isHowler? 'woooooow!': 'woof, woof!';
  162. };
  163. export function Dog(name, breed) {
  164. this.bark = function() {
  165. return name + ': ' + getBarkStyle(breed === 'husky');
  166. };
  167. }
  168. export function Wolf(name) {
  169. this.bark = function() {
  170. return name + ': ' + getBarkStyle(true);
  171. };
  172. }
  173. </code></pre>
  174. <p>Note that now we can have more than one <code>export</code> per module. This way, the client code can choose which functions it wants to <code>import</code> from the module:</p>
  175. <p><strong>main.js:</strong></p>
  176. <pre><code class="lang-javascript">import { Dog, Wolf } from './zoo';
  177. var myDog = new Dog('Sherlock', 'beagle');
  178. console.log(myDog.bark()); // Sherlock: woof, woof!
  179. var myWolf = new Wolf('Werewolf');
  180. console.log(myWolf.bark()); // Werewolf: woooooow!
  181. </code></pre>
  182. <p>This code is also available as a <a href="http://tiagorg.com/js-modules/es6/index.html">live example of an ES6 module</a>. Make sure to <a href="https://github.com/tiagorg/js-modules/tree/gh-pages/es6">check the source code</a>.
  183. Not only ES6 has brought modules, but it also brought a solution for the CommonJS vs AMD battle! According to this <a href="http://www.2ality.com/2014/09/es6-modules-final.html">Dr. Axel Rauschmayer's article</a>, ES6 modules will support both synchronous and asynchronous loading within the same syntax. And even better, they will work both on the browser and on the server!</p>
  184. <p>One more piece of good news: this syntax is finalized, so further syntax changes aren't expected for ES6 Modules. This means that you can start learning it right now!</p>
  185. <h2 id="babel-to-the-rescue">Babel to the rescue</h2>
  186. <p>Using ES6 modules sound thrilling, but since they are targeted for June 2015, what can you do before it gets released and adopted by all the major browsers and devices?</p>
  187. <p>Enter <a href="https://babeljs.io/">Babel</a>, my personal choice of ES6 to ES5 transpiler (a transpiler is a source-to-source compiler, i.e., it will transform ES6 source code into ES5 source code). Babel works for both client-side and server-side JavaScript.</p>
  188. <p>To implement the example above, I am using the <a href="https://github.com/babel/babelify">Babelify plugin</a> over Browserify to transform the ES6 source code directly into an ES5 browser bundle. However, it would be just as simple to transpile the files individually, if you are curious to know how the ES5 source would be. You can even choose it to be transpiled to a specific format, like Common.js or AMD! All you would need to do is:</p>
  189. <pre><code class="lang-bash">npm install -g babel
  190. babel --modules common zoo.js -o zoo-commonjs.es6
  191. babel --modules amd zoo.js -o zoo-amd.es6
  192. </code></pre>
  193. <p>Since in a real project you are hopefully not transpiling files manually, but instead adopting some build system to do that for you, you will be very happy to know that Babel supports most of builders and assets pipelines, and even Rails is on the list! Check out how Babel integrates with your <a href="https://babeljs.io/docs/using-babel/#build-systems">favorite asset pipeline</a>.</p>
  194. <h2 id="who-you-gonna-call-">Who you gonna call?</h2>
  195. <p>Modules are a big deal for sure. All the most successful MV* frameworks rely on a strong module-oriented architecture, such as AngularJS, Ember.js, Marionette.js and React. This is why the JavaScript community is so concerned with helping everyone use them as seamless as possible, as you can see with the ES6 modules initiative.</p>
  196. <p>However, we still have to take into consideration the plethora of existing code which is too big to be rewritten into ES6 anytime soon. Depending on the size, complexity and risk of the project, this might never happen. Still, even if all the major browsers start supporting ES6 this year, it would take a handful of years for most of the worldwide population (or at least your clients) to be effectively using those browser versions supporting ES6. Just for an example [cue the sad-trombone], IE 8 was released exactly 6 years ago.</p>
  197. <p>Anyhow, the other way around is totally feasible and recommended. Writing new code on ES6 with a good transpiler is totally worth taking a deep look at. The benefits are great: more concise syntax, great support for the current Module strategies, and the best thing: you are embracing the future of JavaScript!</p>
  198. <p>When in doubt, remember that Fortune favors the brave. Or just remember Ghostbusters: I ain't afraid of no ghost.</p>