Tim Ambler and Nicholas Cloud JavaScript Frameworks for Modern Web Dev Tim Ambler Nicholas Cloud Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com/ . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . ISBN 978-1-48420663-8 e-ISBN 978-1-4842-0662-1 DOI 10.1007/978-1-4842-0662-1 © Apress 2015 JavaScript Frameworks for Modern Web Dev Managing Director: Welmoed Spahr Lead Editor: Louise Corrigan Technical Reviewer: Robin Hawkes Editorial Board: Steve Anglin, Mark Beckner, Gary Cornell, Louise Corrigan, James DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing, Matt Wade, Steve Weiss Coordinating Editor: Kevin Walter Copy Editor: Bill McManus Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Cover Designer: Crest For information on translations, please e-mail [email protected], or visit www.apress.com . Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales . This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800- SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. There was a young lady named Laura, Who was a beautiful señora. Her love and assurance Was a frequent occurrence Which allowed me to write this book for yah. —Tim Dedicated to Brittany who supported me and gave me space during the long hours that writing demands. —Nicholas Introduction They tell me we’re living in an information age, but none of it seems to be the information I need or brings me closer to what I want to know. In fact (I’m becoming more and more convinced) all this electronic wizardry only adds to our confusion, delivering inside scoops and verdicts about events that have hardly begun: a torrent of chatter moving at the speed of light, making it nearly impossible for any of the important things to be heard. —Matthew Flaming, The Kingdom of Ohio The notion that “technology moves quickly” is a well-worn aphorism, and with good reason: technology does move quickly. But at this moment, JavaScript in particular is moving very quickly indeed—much like that “torrent of chatter moving at the speed of light” that Matthew Flaming refers to in The Kingdom of Ohio. The language is in the midst of what many have called a renaissance, brought about by the rapidly increasing sophistication of browser-based applications and the rising popularity of JavaScript on the server, thanks to Node.js. An almost feverish pace of innovation is occurring within the JavaScript community that, while endlessly fascinating to follow, also presents some unique challenges of its own. JavaScript’s ecosystem of libraries, frameworks, and utilities has grown dramatically. Where once a small number of solutions for any given problem existed, many can now be found… and the options continue to grow by the day. As a result, developers find themselves faced with the increasingly difficult task of choosing the appropriate tools from among many seemingly good options. If you’ve ever found yourself wondering why JavaScript seems to be attracting so much attention lately, as we have, it’s worth stopping for a moment to consider the fact that JavaScript, a language that was created by one person in ten days, now serves as the foundation upon which much of the Web as we know it sits. A language that was originally created to solve relatively simple problems is now being applied in new and innovative ways that were not originally foreseen. What’s more, JavaScript is a beautifully expressive language, but it’s not without its share of rough edges and potential pitfalls. While flexible, efficient, and ubiquitous, JavaScript concepts such as the event loop and prototypal inheritance can prove particularly challenging for those coming to the language for the first time. For these and many other reasons, the development community at large is still coming to terms with how best to apply the unique features that JavaScript brings to the table. We’ve no doubt only scratched the surface of what the language and the community behind it are capable of. For those with an insatiable appetite for knowledge and a desire to create, now is the perfect time to be a JavaScript developer. We have written Pro JavaScript Frameworks for Modern Web Dev to serve as your guide to a wide range of popular JavaScript tools that solve difficult problems at both ends of the development stack: in the browser and on the server. The tutorials and downloadable code examples contained within this book illustrate the usage of tools that manage dependencies, structure code in a modular fashion, automate repetitive build tasks, create specialized servers, structure client side applications, facilitate horizontal scaling, perform event logging, and interacting with disparate data stores. The libraries and frameworks covered include Bower, Grunt, Yeoman, PM2, RequireJS, Browserify, Knockout, AngularJS, Kraken, Mach, Mongoose, Knex, Bookshelf, Faye, Q, Async.js, Underscore, and Lodash. In writing Pro JavaScript Frameworks for Modern Web Dev, our goal was to create a filter for the “torrent of chatter” that often seems to surround JavaScript, and in so doing, to allow what we believe are some important things to be heard. We hope the information contained within these pages proves as useful to you as it has to us. Who This Book Is For This book is intended for web developers who are already confident with JavaScript, but also frustrated with the sheer number of solutions that exist for seemingly every problem. This book helps lift the fog, providing the reader with an in-depth guide to specific libraries and frameworks that well-known organizations are using right now with great success. Topics pertaining to both client-side and server-side development are covered. As a result, readers will gain the most benefit from this book if they already have at least an intermediate familiarity with both the web browser Document Object Model (DOM), common client-side libraries like jQuery, and Node.js. How This Book Is Structured This book covers a wide selection of JavaScript tools that are applicable throughout the entire development process, from a project’s first commit to its first release and beyond. To that end, the chapters have been grouped into the following parts. Part 1: Development Tools Bower Dependency management is hardly a new idea - well-known examples include Node’s npm, Python’s pip, and PHP’s composer. A practice that has only recently begun to see widespread adoption, however, is the application of this concept to the management of front-end web assets - the JavaScript libraries, stylesheets, fonts, icons, and images that serve as the building blocks of modern web applications. In this chapter, we’ll discover several ways in which Bower - a popular tool within this field - can improve your development process by providing you with a mechanism for organizing these dependencies within your application. Grunt Larry Wall, the creator of Perl, describes the three virtues of a great programmer as: laziness, impatience, and hubris. In this chapter, we’ll focus on a tool that will help you strengthen the virtue of laziness - Grunt. This popular task runner provides developers with a framework for creating command-line utilities that automative repetitive build tasks such as running tests, concatenating files, compiling SASS / LESS stylesheets, checking for JavaScript errors, and more. After reading this chapter, you’ll know how to use several popular Grunt plugins, as well as how to go about creating and sharing your own plugins with the community. Yeoman Yeoman provides JavaScript developers with a mechanism for creating reusable templates (“generators”) that describe the overall structure of a project (initially required dependencies, Grunt tasks, etc…) in a way that can be easily re-used over and over. Broad community support also allows you to take advantage of a wide variety of pre-existing templates. In this chapter, we’ll walk through the process of installing Yeoman and using several popular pre-existing generators. Finally, we’ll take a look at how we can create and share our own templates with the community. PM2 In this chapter, we will close out our discussion of development tools by taking a look at PM2, a command-line utility that simplifies many of the tasks associated with running Node applications, monitoring their status, and efficiently scaling them to meet increasing demand. Part 2: Module Loaders RequireJS and Browserify JavaScript’s lacks a native method for loading external dependencies in the browser—a frustrating oversight for developers. Fortunately, the community has stepped in to fill this gap with two very different and competing standards: the Asynchronous Module Definition (AMD) API and CommonJS. We’ll dive into the details of both and take a look at widely-used implementations of each: RequireJS and Browserify. Each have their merits, which we’ll discuss in detail, but both can have a profoundly positive impact on the way in which you go about structuring your applications. Part 3: Client-Side Frameworks Knockout and AngularJS In recent years, web developers have witnessed a sharp rise in popularity of so- called “single-page apps.” Such applications exhibit behavior once available only on the desktop, but at the expense of increased code complexity within the browser. In this section, we’ll dive into two widely-used front-end frameworks that help minimize that complexity by providing proven patterns for solving frequently-encountered problems: Knockout and AngularJS. Knockout focuses on the relationship between view and data, but otherwise leaves the application architecture and plumbing to the developer’s discretion. AngularJS takes a more prescriptive approach, covering the view, application routing, data transfer, and module design. Part 4: Server-Side Frameworks Kraken and Mach Client-side applications aren’t very useful without a server with which to interact. In this section, we’ll take a look at two popular frameworks that support developers in the creation of back-end applications: Kraken and Mach. Mach is more than just a simple web server: it is HTTP for the web. Mach
Description: