38,39 €
An in-depth guide to exploring the design, architecture, and techniques behind building sophisticated, scalable, and maintainable single-page applications in JavaScript
This book is ideal for JavaScript developers who want to build complex single-page applications in JavaScript. Some basic understanding of SPA concepts will be helpful but not essential.
Single-page web applications—or SPAs, as they are commonly referred to—are quickly becoming the de facto standard for web app development. The fact that a major part of the app runs inside a single web page makes it very interesting and appealing. Also, the accelerated growth of browser capabilities is pushing us closer to the day when all apps will run entirely in the browser.
This book will take your JavaScript development skills to the next level by teaching you to create a single-page application within a full-stack JavaScript environment. Using only JavaScript, you can go from being a front-end developer to a full-stack application developer with relative ease.
You will learn to cross the boundary from front-end development to server-side development through the use of JavaScript on both ends. Use your existing knowledge of JavaScript by learning to manage a JSON document data store with MongoDB, writing a JavaScript powered REST API with Node.js and Express, and designing a front-end powered by AngularJS.
This book will teach you to leverage the MEAN stack to do everything from document database design, routing REST web API requests, data-binding within views, and adding authentication and security to building a full-fledged, complex, single-page web application.
In addition to building a full-stack JavaScript app, you will learn to test it with JavaScript-powered testing tools such as Mocha, Karma, and Jasmine. Finally, you will learn about deployment and scaling so that you can launch your own apps into the real world.
Following a structured approach, this book helps readers gain expertise in SPA development. Its thorough coverage of SPA architecture and design, along with practical use cases, provides readers with a clear path to building applications with the library of their choice. For readers who are afraid to take the plunge straightaway, the book also offers step-by-step guidance on developing a complex web app.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 490
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2016
Production reference: 1241016
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-164-0
www.packtpub.com
Authors
Philip Klauzinski
John Moore
Copy Editor
Safis Editing
Reviewers
Ciro Artigot
Project Coordinator
Ritika Manoj
Commissioning Editor
Wilson D'souza
Proofreader
Safis Editing
Acquisition Editor
Reshma Raman
Indexer
Rekha Nair
Content Development Editor
Divij Kotian
Graphics
Jason Monteiro
Technical Editor
Sachit Bedi
Production Coordinator
Aparna Bhagat
Philip Klauzinski is a senior frontend developer specializing in JavaScript Single Page Application (SPA) development. He has over 20 years of experience in web design and web development and is a leading expert in web application development, client-side JavaScript, and Search Engine Optimization (SEO). Philip has worked as a frontend developer across multiple industries, including consumer e-commerce, business-to-business e-commerce, big data, Web hosting, direct marketing, domain name services (DNS), and manufacturing.
I would like to thank my Mom and Dad for always stressing the importance of education in my life, not just institutional education, but more importantly, the pursuance of self-education. My own interest in technology and software from a young age has driven my subsequent, self-taught approach to my career. As a result, I love what I do for a living, and I have been able to shape my professional life around the things in which I am truly interested. I am inherently driven to learn more every day, and I believe that is what has led to my success. Thank you, Mom and Dad!
John Moore has been working in web development for 20 years. He is an industry expert in JavaScript and HTML5. He has developed award-winning web applications and worked and consulted for Digital Equipment Corporation, Ernst & Young, Wachovia Bank, and Fidelity Investments. Having focused his early career on frontend web development, he helped usher in responsive web design and Single Page Applications in his roles in development and architecture. Most recently, he led Full Stack development in JavaScript, serving as CTO of a Maine-based startup company.
I would like to thank my wife, Dr. Myra Salapare, and daughters, Mila Moore and Sophia Moore, for all of their support. I would also like to thank Andrea Shiflet, Erin Benner, and Lauren Grousd for their tremendous help.
Ciro Artigot is currently working as an IT manager at ECODES, an Spanish foundation that works for the welfare of all people within the limits of our planet.
He has developed websites for over 15 years. He is a Full Stack developer and CMS expert and is addicted to Joomla, He has worked for 10 years in open source GNU projects, mainly in LAMP .
For the last few years, he has been investigating and working with SPA in MEAN environments.
I would like to thank Pampa, Diego,and Hugo, for giving me the time to review this book, and my parents and brothers, for making it possible for me to devote myself to what I like best—develop
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Created in 1995 by Brendan Eich of Netscape, JavaScript has gone from being a toy scripting language used only in browsers to being one of the most popular languages in the world for full-stack development. With the introduction of Node.js, built on top of Chrome’s V8 JavaScript Engine, developers are now able to build powerful and performant applications using JavaScript. With the addition of MongoDB, a modern NoSQL database, applications can utilize JavaScript at every tier.
Many popular web applications are implemented, partially or in whole, as single-page applications, or SPAs. With SPAs, users load a single web page, and that page is updated dynamically in response to user interaction or incoming server data. The advantage is an application experience that is smoother, replicates native application interaction, and may require less network traffic and server load.
The MEAN stack is a set of JavaScript tools representing a full stack, from database to runtime environment, application framework, and frontend. This book provides a thorough background in building SPAs using the MEAN stack and other tools in the JavaScript ecosystem. It covers the basics of SPA architecture and JavaScript tools. The book then expands to more advanced topics, such as building, securing, and deploying an SPA built with the MEAN stack.
Chapter 1, Getting Organized NPM, Bower, and Grunt, introduces JavaScript frontend package-management, build, and task-running tools. These tools form the foundation for you to set up an ideal development environment.
Chapter 2, Model-View-Whatever, goes beyond the original MVC design pattern and explores its translation into frontend frameworks and its evolution into Model-View-*, or Model-View-Whatever (MVW), in which the Controller layer is more open ended and often abstracted into other layers more suited to an SPA environment.
Chapter 3, SPA Essentials - Creating the Ideal Application Environment, introduces you to the common components/layers of an SPA, the best practices and variations around these components, and how to put them together and lay the groundwork for a modern SPA.
Chapter 4, REST is Best - Interacting with the Server Side of Your Application, goes into further detail about the server side of SPA architecture—in particular, with regard to the REST (representational state transfer) architectural pattern. You’ll become familiar with different methods to interact with a REST API using JavaScript and AJAX, with practical examples.
Chapter 5, Its All About the View, focuses on the concept of views in the SPA architecture and how views can be initialized in a single-page container. It discusses JavaScript templates and provides examples from different libraries, going deeper into how AngularJS views are implemented.
Chapter 6, Data Binding, and Why You Should Embrace It, teaches you about data binding, describes one-way versus two-way data binding, and discusses the practicality of data binding in an SPA and why you should use it. You will also cover the continual evolution of the ECMAScript/JavaScript standard and how it now supports native data binding in some clients.
Chapter 7, Leveraging the MEAN Stack, introduces you to the MEAN stack (MongoDB, Express, AngularJS, and Node.js) and how they work together. You will install and configure MongoDB and Node.js and explore working with each on the command line. You’ll create a database for a new SPA and learn about AngularJS and Express, the two other pieces of the stack.
Chapter 8, Manage Data Using MongoDB, teaches you how to create and manage databases in MongoDB. Using the command line, you will execute CRUD (create, read, update, and delete) functions.
Chapter 9, Handling Web Requests with Express, familiarizes you with the Express routing middleware and handling requests from and responses to the browser. After configuring the Express router, you’ll create a number of routes, which return dynamically generated data to the web browser when requested, organize your routes logically, and handle POST requests from forms.
Chapter 10, Displaying Views, explores combining dynamic view rendering in Express along with AngularJS. You will configure the Express application to use EJS (Embedded JavaScript) templates and use Bootstrap for basic styling.
Chapter 11, Adding Security and Authentication, teaches you how to secure the Express-based SPA by preventing common exploits such as cross-site request forgery (CSRF). You will install passport-authentication middleware for Node.js and configure it for local authentication and set up session management.
Chapter 12, Connecting the App to Social Media, extends the SPA by connecting it to multiple social media platforms. You will set up passport authentication using Facebook and Twitter strategies and share data from the SPA.
Chapter 13, Testing with Mocha, Karma, and More, teaches you testing, both on the server side and in the view.
Chapter 14, Deploying and Scaling the SPA, walks you through setting up a production database on MongoLab and deploying your SPA to Heroku. Finally, you will explore scaling your SPA in the cloud.
The book requires very few pieces of software besides your web browser and your operating system's command line or terminal. You will need an editor for writing code. Any text editor will do, from Notepad to an IDE such as Jetbrains WebStorm.
This book is ideal for JavaScript developers who want to build complex SPAs in JavaScript. Some basic understanding of SPA concepts will be helpful but are not essential.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-JavaScript-Single-Page-Application-Development. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
JavaScript was the bane of the web development industry during the early days of the browser-rendered Internet. It now powers hugely impactful libraries such as jQuery, and JavaScript-rendered (as opposed to server-side-rendered) content is even indexed by many search engines. What was once largely considered an annoying language used primarily to generate pop-up windows and alert boxes, has now become arguably the most popular programming language in the world.
Not only is JavaScript now more prevalent than ever in frontend architecture, but it has become a server-side language as well, thanks to the Node.js runtime. We have also seen the proliferation of document-oriented databases, such as MongoDB, which store and return JSON data. With JavaScript present throughout the development stack, the door is now open for JavaScript developers to become full-stack developers without the need to learn a traditional server-side language. Given the right tools and know-how, any JavaScript developer can create single page applications comprised entirely of the language they know best, and they can do so using an architecture like MEAN (MongoDB, Express, AngularJS, and Node.js).
Organization is key to the development of any complex Single Page Application (SPA). If you don't get organized from the beginning, you are sure to introduce an inordinate number of regressions to your app. The Node.js ecosystem will help you to do this with a full suite of indispensable and open-source tools, three of which we will discuss here.
In this chapter, you will learn about:
Within any full-stack JavaScript environment, Node Package Manager will be your go-to tool for setting up your development environment and for managing server-side libraries. NPM can be used within both global and isolated environment contexts. We will first explore the use of NPM globally.
NPM is a component of Node.js, so before you can use it you must first install Node.js. You can find installers for both Mac and Windows at nodejs.org. Once you have Node.js installed, using NPM is incredibly easy and is done from the Command Line Interface (CLI). Start by ensuring you have the latest version of NPM installed, as it is updated more often than Node.js itself:
$ npm install -g npmWhen using NPM, the -g option will apply your changes to your global environment. In this case, you want your version of NPM to apply globally. As stated previously, NPM can be used to manage packages both globally and within isolated environments. In the following, we want essential development tools to be applied globally so that you can use them in multiple projects on the same system.
With Mac and some Unix-based systems, you may have to run the npm command as the superuser (prefix the command with sudo) in order to install packages globally, depending on how NPM was installed. If you run into this issue and wish to remove the need to prefix npm with sudo, see docs.npmjs.com/getting-started/fixing-npm-permissions.
For any project you develop, you will keep a local package.json file to manage your Node.js dependencies. This file should be stored at the root of your project directory and it will only pertain to that isolated environment. This allows you to have multiple Node.js projects with different dependency chains on the same system.
When beginning a new project, you can automate the creation of the package.json file from the command line:
$ npm initRunning npm init will take you through a series of JSON property names to define through command line prompts, including your app's name, version number, description, and more. The name and version properties are required, and your Node.js package will not install without them defined. Several of the properties will have a default value given within parentheses in the prompt so that you may simply hit Enter to continue. Other properties will simply allow you to hit Enter with a blank entry and will not be saved to the package.json file, or will be saved with a blank value:
name: (my-app)version: (1.0.0)description:entry point: (index.js)The entry point prompt will be defined as the main property in package.json and is not necessary unless you are developing a Node.js application. In our case, we can forgo this field. The npm init command may in fact force you to save the main property, so you will have to edit package.json afterward to remove it; however, that field will have no effect on your web app.
You may also choose to create the package.json file manually using a text editor, if you know the appropriate structure to employ. Whichever method you choose, your initial version of the package.json file should look similar to the following example:
{ "name": "my-app", "version": "1.0.0", "author": "Philip Klauzinski", "license": "MIT", "description": "My JavaScript single page application." }If you want your project to be private and want to ensure that it does not accidently get published to the NPM registry, you may want to add the private property to your package.json file, and set it to true. Additionally, you may remove some properties that only apply to a registered package:
{ "name": "my-app", "author": "Philip Klauzinski", "description": "My JavaScript single page application.", "private": true }Once you have your package.json file set up the way you like it, you can begin installing Node.js packages locally for your app. This is where the importance of dependencies begins to surface.
There are three types of dependencies that can be defined for any Node.js project in your package.json file: dependencies, devDependencies, and peerDependencies. For the purpose of building a web-based SPA, you will only need to use the devDependencies declaration.
devDependencies are those which are required for developing your application, but not required for its production environment or for simply running it. If other developers want to contribute to your Node.js application, they will need to run npm install from the command line to set up the proper development environment. For information on the other types of dependencies, see docs.npmjs.com.
When adding devDependencies to your package.json file, the command line again comes to the rescue. Let's use the installation of Browserify as an example:
$ npm install browserify --save-devThis will install Browserify locally and save it along with its version range to the devDependencies object in your package.json file. Once installed, your package.json file should look similar to the following example:
{ "name": "my-app", "version": "1.0.0", "author": "Philip Klauzinski", "license": "MIT", "devDependencies": { "browserify": "^12.0.1" } }The devDependencies object will store each package as a key-value pair in which the key is the package name and the value is the version number or version range. Node.js uses semantic versioning, where the three digits of the version number represent MAJOR.MINOR.PATCH. For more information on semantic version formatting, see semver.org.
You will notice that the version number of the installed package is preceded by a caret (^) symbol by default. This means that package updates will only allow patch and minor updates for versions above 1.0.0. This is meant to prevent major version changes from breaking your dependency chain when updating your packages to the latest versions.
To update your devDependencies and save the new version numbers, you can enter the following from the command line:
$ npm update --save-devAlternatively, you can use the -D option as a shortcut for --save-dev:
$ npm update -DTo update all globally installed NPM packages to their latest versions, run npm update with the -g option:
$ npm update -gFor more information on semantic versioning within NPM, see docs.npmjs.com/misc/semver.
Now that you have NPM set up and you know how to install your development dependencies, you can move on to installing Bower.
Bower is a package manager for frontend web assets and libraries. You will use it to maintain your frontend stack and control version chains for libraries such as jQuery, AngularJS, and any other components necessary to your app's web interface.
Bower is also a Node.js package, so you will install it using NPM, much like you did with the Browserify example installation in the previous section, but this time you will be installing the package globally. This will allow you to run bower from the command line anywhere on your system without having to install it locally for each project:
$ npm install -g bowerYou can alternatively install Bower locally as a development dependency so that you may maintain different versions of it for different projects on the same system, but this is generally not necessary:
$ npm install bower --save-devNext, check that Bower is properly installed by querying the version from the command line:
$ bower -vBower also requires a Git version control system, or VCS, to be installed on your system in order to work with packages. This is because Bower communicates directly with GitHub for package management data. If you do not have Git installed on your system, you can find instructions for Linux, Mac, and Windows at git-scm.com.
The process of setting up your bower.json file is comparable to that of the package.json file for NPM. It uses the same JSON format, has both dependencies and devDependencies, and can also be automatically created:
$ bower initOnce you type bower init from the command line, you will be prompted to define several properties with some defaults given within parentheses:
? name: my-app ? version: 0.0.0 ? description: My app description. ? main file: index.html ? what types of modules does this package expose? (Press <space> to? what types of modules does this package expose? globals ? keywords: my, app, keywords ? authors: Philip Klauzinski ? license: MIT ? homepage: http://gui.ninja ? set currently installed components as dependencies? No ? add commonly ignored files to ignore list? Yes ? would you like to mark this package as private which prevents it from being accidentally published to the registry? YesThese questions may vary, depending on the version of Bower you install.
Most properties in the bower.json file are not necessary unless you are publishing your project to the Bower registry, indicated in the final prompt. You will most likely want to mark your package as private, unless you plan to register it and allow others to download it as a Bower package.
Once you have created the bower.json file, you can open it in a text editor and change or remove any properties you wish. It should look something like the following example:
{ "name": "my-app", "version": "0.0.0", "authors": [ "Philip Klauzinski" ], "description": "My app description.", "main": "index.html", "moduleType": [ "globals" ], "keywords": [ "my", "app", "keywords" ], "license": "MIT", "homepage": "http://gui.ninja", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ], "private": true }If you wish to keep your project private, you can reduce your bower.json file to two properties before continuing:
{ "name": "my-app", "private": true }Once you have the initial version of your bower.json file set up the way you like it, you can begin installing components for your app.
Bower will install components into a directory named bower_components by default. This directory will be located directly under the root of your project. If you wish to install your Bower components under a different directory name, you must create a local system file named .bowerrc and define the custom directory name there:
{ "directory": "path/to/my_components" }An object with only a single directory property name is all that is necessary to define a custom location for your Bower components. There are many other properties that can be configured within a .bowerrc file. For more information on configuring Bower, see bower.io/docs/config/.
Bower also allows you to define both the dependencies and devDependencies objects like NPM. The distinction with Bower, however, is that the dependencies object will contain the components necessary for running your app, while the devDependencies object is reserved for components that you might use for testing, transpiling, or anything that does not need to be included in your frontend stack.
Bower packages are managed using the bower command from the CLI. This is a user command, so it does not require super user (sudo) permissions. Let's begin by installing jQuery as a frontend dependency for your app:
$ bower install jquery --saveThe --save option on the command line will save the package and version number to the dependencies object in bower.json. Alternatively, you can use the -S option as a shortcut for --save:
$ bower install jquery -SNext, let's install the Mocha JavaScript testing framework as a development dependency:
$ bower install mocha --save-devIn this case, we will use --save-dev on the command line to save the package to the devDependencies object instead. Your bower.json file should now look similar to the following example:
{ "name": "my-app", "private": true, "dependencies": { "jquery": "~2.1.4" }, "devDependencies": { "mocha": "~2.3.4" } }Alternatively, you can use the -D option as a shortcut for --save-dev:
$ bower install mocha -DYou will notice that the package version numbers are preceded by the tilde (~) symbol by default, in contrast to the caret (^) symbol as is the case with NPM. The tilde serves as a more stringent guard against package version updates. With a MAJOR.MINOR.PATCH version number, running bower update will only update to the latest patch version. If a version number is composed of only the major and minor versions, bower update will update the package to the latest minor version.
All registered Bower components are indexed and searchable through the command line. If you don't know the exact package name of a component you wish to install, you can perform a search to retrieve a list of matching names.
Most components will have a list of keywords in their bower.json file so that you can more easily find the package without knowing the exact name. For example, you may want to install PhantomJS for headless browser testing:
$ bower search phantomjsThe list returned will include any package with phantomjs in the package name or within its keywords list:
phantom git://github.com/ariya/phantomjs.git dt-phantomjs git://github.com/keesey/dt-phantomjs qunit-phantomjs-runner git://github.com/jonkemp/... parse-cookie-phantomjs git://github.com/sindresorhus/... highcharts-phantomjs git://github.com/pesla/highcharts-phantomjs.git mocha-phantomjs git://github.com/metaskills/mocha-phantomjs.git purescript-phantomjs git://github.com/cxfreeio/purescript-phantomjs.gitYou can see from the returned list that the correct package name for PhantomJS is in fact phantom and not phantomjs. You can then proceed to install the package now that you know the correct name:
$ bower install phantom --save-devNow you have Bower installed and know how to manage your frontend web components and development tools, but how do you integrate them into your SPA? This is where Grunt comes in.
