JavaScript Frameworks for Modern Web Development The Essential Frameworks, Libraries, and Tools to Learn Right Now — Second Edition — Sufyan bin Uzayr Nicholas Cloud Tim Ambler www.com JavaScript Frameworks for Modern Web Development The Essential Frameworks, Libraries, and Tools to Learn Right Now Second Edition Sufyan bin Uzayr Nicholas Cloud Tim Ambler www.com JavaScript Frameworks for Modern Web Development Sufyan bin Uzayr Nicholas Cloud Al Manama, United Arab Emirates Florissant, MO, USA Tim Ambler Nashville, TN, USA ISBN-13 (pbk): 978-1-4842-4994-9 ISBN-13 (electronic): 978-1-4842-4995-6 https://doi.1007/978-1-4842-4995-6 Copyright © 2019 by Sufyan bin Uzayr, Nicholas Cloud, Tim Ambler 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. 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. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Louise Corrigan Development Editor: James Markham Coordinating Editor: Nancy Chen Cover designed by eStudioCalamar 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 orders-ny@springer- sbm.com, or visit www. 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. For information on translations, please e-mail rights@apress.com, or visit http://www.com/ rights-permissions.
Apress titles 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 Print and eBook Bulk Sales web page at http://www.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at www.
For more detailed information, please visit http://www.com/source-code. Printed on acid-free paper www.com For Anza —Sufyan bin Uzayr www.com Table of Contents About the Authors.xv About the Technical Reviewer .xxi Part I: Development Tools. 4 How Grunt Works. 8 Adding Grunt to Your Project.
8 Maintaining a Sane Grunt Structure. 9 Working with Tasks. 16 Multi-Task Options. 19 Command-Line Options .com TABLE OF CONTENTS Interacting with the File System.
22 Source-Destination Mappings. 23 Watching for File Changes. 31 Creating the Task. 32 Publishing to npm.
40 Creating Your First Project. 44 Creating Your First Generator. 45 Yeoman Generators Are Node Modules. 47 Defining Secondary Commands.
61 Working with Processes. 62 Recovering from Errors. 65 Responding to File Changes. 68 Monitoring Resource Usage.
70 Monitoring Local Resources. 70 Monitoring Remote Resources. 71 vi TABLE OF CONTENTS Advanced Process Management. 75 JSON Application Declarations.
75 Load Balancing Across Multiple Processors. 81 Zero Downtime Deployments. 87 Part II: Module Loaders. 91 Running the Examples.
93 Working with RequireJS. 95 Application Modules and Dependencies. 99 Paths and Aliases. 133 The AMD API vs.
135 Creating Your First Bundle. 136 Visualizing the Dependency Tree. 138 Creating New Bundles As Changes Occur. 139 Watching for File Changes with Grunt.
139 Watching for File Changes with Watchify. 140 vii TABLE OF CONTENTS Using Multiple Bundles. 142 The Node Way. 147 Module Resolution and the NODE_PATH Environment Variable.
152 Defining Browser-Specific Modules. 153 Extending Browserify with Transforms. 160 Part III: Client-Side Frameworks. 163 Views, Models, and View Models.
164 The Recipe List. 171 Binding View Models to the DOM. 175 View Models and Forms. 177 Switching to “Edit” Mode.
178 Changing the Recipe Title. 182 Updating Recipe Servings and Cooking Time. 183 Adding and Removing Ingredients. 196 The Input List View Model.
197 The Input List Template. 199 Registering the Input List Tag. 201 viii TABLE OF CONTENTS Subscribables: Cheap Messaging. 209 Differences Between Angular and AngularJS.
209 Getting Started with Angular. 211 Creating a Workspace in Angular. 215 Serving the App. 216 Customizing the App.
217 Dependency Injection in Angular. 221 Creating and Registering an Injection Service. 223 Part IV: Server-Side Frameworks. 227 Environment-Aware Configuration.
234 Configuration-Based Middleware Registration. 243 Structured Route Registration. 251 Context and References. 259 ix TABLE OF CONTENTS Blocks.
275 Let’s Get Kraken. 306 Part V: Managing Database Interaction. 309 Basic MongoDB Concepts. 309 A Simple Mongoose Example.
314 Creating a Mongoose Schema for JSON Data. 314 Importing Data with Mongoose. 317 Querying Data with Mongoose. 320 Working with Schemas.
325 Default Property Values. 340 Working with Models and Documents. 343 Document Instance Methods. 350 Static Model Methods.
352 Working with Queries. 360 x TABLE OF CONTENTS Model. 363 Finding Documents with Query Operators. 375 Chapter 10: Knex and Bookshelf.
378 Installing the Command-Line Utility. 379 Adding Knex to Your Project. 380 The SQL Query Builder. 400 What Is Object-Relational Mapping?.
401 Creating Your First Bookshelf Model. 426 Part VI: Managing Control Flow. 443 Looping While Some Condition Remains True. 443 Looping Until Some Condition Becomes False.
451 xi TABLE OF CONTENTS Batch Flow. 458 Part VII: Further Useful Libraries. 461 Chapter 12: Underscore and Lodash. 463 Installation and Usage.
465 Aggregation and Indexing. 472 Selecting Data from Collections. 472 Selecting Data from Objects. 493 Loops and Other Arbitrary JavaScript in Templates.
495 Living Without Gator Tags. 497 Accessing the Data Object Within a Template. 499 Default Template Data. 503 xii TABLE OF CONTENTS Part VIII: Front-End Development.
507 What Makes React Special?. 508 Getting Started with React. 509 How to Add React to Web Pages?. 510 Building a To-Do Application.
523 What Is Vue. 523 What Is Vue Meant For?. 524 Getting Started with Vue. 526 Building Our First Vue App.
541 xiii About the Authors Sufyan bin Uzayr is a web developer with over 10 years of experience in the industry. He specializes in a wide variety of technologies, including JavaScript, WordPress, Drupal, PHP, and UNIX/Linux shell and server management, and is the author of five previous books. Sufyan is the Director of Parakozm, a multinational design and development consultancy firm that offers customized solutions to a global clientele. He is also the CTO at Samurai Servers, a server management and security company catering mainly to enterprise-scale audience.
He takes a keen interest in technology, politics, literature, history, and sports, and in his spare time he enjoys teaching coding and English to students. Read more about his works at www. Nicholas Cloud is a software developer who lives in the very humid city of St. For over a decade, he has forged his skills into a successful career.
He has developed web applications, web services, and desktop software on diverse platforms with JavaScript, C#, and PHP. A strong proponent of open source software, Nicholas contributes to userland projects and has written several of his own open source libraries. He speaks at a variety of user groups and conferences and writes books, technical articles, and blog posts in his spare time. He opines on Twitter at @nicholascloud.
xv ABOUT THE AUTHORS Tim Ambler is a software engineer from Nashville, Tennessee. His passion for programming follows in the footsteps of his father, who introduced him to computers at a young age with a Commodore 64. Tim is the author of several popular open source projects, one of which (whenLive) has been featured by GitHub’s staff. An occasional conference speaker and frequent writer, Tim has been referenced multiple times in online publications such as JavaScript Weekly and Node Weekly.
He currently lives in the 12 South area with his wife, Laura, and two cats. You can follow him on Twitter at @tkambler. xvi About the Technical Reviewer Aleemullah Samiullah is a seasoned developer with over 10+ years of experience in front-end technologies. He is a senior engineer at Software AG and has previously worked at Publicis Sapient and Infosys, gaining considerable expertise, working with major brands such as Tesco, Target, and Holt Renfrew.
He enjoys crafting digital experiences based on human-centered design, with a keen focus on usability and accessibility. In his career, Aleem has used various JavaScript libraries, including React, Angular, Backbone, ExtJS, jQuery, and so on. He is passionate about the latest technologies and actively participates in JS meetups and conferences. When he’s not coding, he likes to travel, write blog posts, and spend time with family.
Aleem can be found on LinkedIn at www.com/in/aleemullah/. xvii Acknowledgments There are several people who deserve to be on this page because this book would not have come into existence without their support. That said, some names deserve a special mention, and I am genuinely grateful to • My mom and dad, for everything they have done for me • Faisal Fareed and Sadaf Fareed, my siblings, for helping with things back home • Nancy Chen, Content Development Editor for this book, for keeping track of everything and for being very patient as I kept missing one deadline or the other • The Apress team, especially Louise Corrigan, Jade Scard, and James Markham, for ensuring that the book’s content, layout, formatting, and everything else remains perfect throughout • The coauthors of this book’s first edition and the tech reviewer, for going through the manuscript and providing his insight and feedback • Typesetters, cover designers, printers, and everyone else, for their part in the development of this book • All the folks associated with Parakozm, either directly or indirectly, for their help and support • The JavaScript community at large, for all their hard work and efforts —Sufyan bin Uzayr xix 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.