38,39 €
Harness the power of the next-generation JavaScript Framework, Aurelia, and start creating apps that really set you apart
This book is for JavaScript developers who want to build modern web apps with Aurelia. No prior knowledge of Aurelia is needed.
Aurelia is one of the most promising new JavaScript frameworks for mobile, desktop, and web, which makes developing powerful, modern web applications a straightforward task. Its power lies in its simplicity and clear workflow that enables developers to build next-generations apps for the web with ease.
From initial structuring to full deployment, this book will serve as a step-by-step guide to develop a modern web application from scratch with the Aurelia framework. In addition to including a comprehensive coverage of various Aurelia framework features, this book will also show you how to utilize these features in the real world to develop a professional single-page web application. You'll see how to make the most out of Aurelia by understanding the Aurelia workflow and then applying it in real-world development tasks. By the end of the book, you will have learned to develop a clean and maintainable application in Aurelia from scratch.
This book will show you how to leverage the cutting edge features of Aurelia framework to develop modern web apps with a clear workflow. Using the modern architecture and features of Aurelia, this book will demonstrate the development of a web application from scratch.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 522
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 author(s), 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: December 2016
Production reference: 1221216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-967-7
www.packtpub.com
Author
Manuel Guilbault
Copy Editor
Safis Editing
Reviewer
Matthew James Davis
Project Coordinator
Sheejal Shah
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Smeet Thakkar
Indexer
Tejal Daruwale Soni
Content Development Editor
Parshva Sheth
Graphics
Abhinash Sahu
Technical Editor
Prashant Mishra
Production Coordinator
Shantanu N. Zagade
Manuel Guilbault is a Canadian-born, France-based developer, and works as the CTO of an online marketing startup. After studying software engineering in Montreal, he worked as a full-stack web developer for well-known clients in the press industry, automotive industry, and financial sector for 10 years.
An Aurelia enthusiast since day one, he closely followed the development of the framework, while modestly contributing to it and blogging and talking about it. He is an active member of the Paris Aurelia meetup group.
Passionate about software craftsmanship, agility, and lean principles, he loves to learn and debate about how we do things, why we do them this way, and how they can be improved.
I’d like to thank my friends and family for their tremendous support and enthusiasm for this project. Kudos to Geoffrey for his patience, for all the times I let him handle business issues so I could work on this book, and to Frank for the review and advice. Lastly, my gratitude to my wife, Caroline, who lovingly went through the countless weekends during which I researched and wrote instead of spending time with her.
Matthew James Davis is a friendly guy who loves his family and enjoys writing exceptional code. He has been involved with Aurelia since its inception and regularly writes Aurelia-related blogs on his website, http://davismj.me/.
I’d like to thank my two mentors in the software world: Brian Hearn and Rob Eisenberg.
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.
Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].
The Web evolves very quickly. Technologies come and go, and every couple of years, new ideas emerge and become widely popular, only to be replaced by something else after a while.
If you’ve been doing web development for many years, chances are you’ve seen this cycle go on. Things such as Prototype, and then jQuery, were widely popular in the mid-2000s, and are still used on many projects nowadays.
Then, with the performance of browsers and JavaScript engines getting better and better, the last decade or so have seen the emergence of many full-blown, JavaScript-based frontend frameworks such as Angular and Durandal. More recently, modern frameworks based on different concepts or paradigms such as React and Polymer have gained a lot of popularity.
Aurelia is such a modern framework. The brainchild of Rob Eisenberg, the father of Durandal, it is based on cutting edge Web standards, and is built on modern software architecture concepts and ideas, to offer a powerful toolset and an awesome developer experience.
Chapter 1, Getting Started, walks you through the basic concepts around Aurelia, and explains how to set up your environment and start a project.
Chapter 2, Layout, Menu, and Getting Familiar, goes further into the concepts at the core of Aurelia, such as dependency injection, logging, and the plugin system. It also explains how to create the main layout and navigation menu of a multi-paged application.
Chapter 3, Displaying Data, guides you through the templating and data-binding system, so you can build complex views.
Chapter 4, Forms, and How to Validate Them, builds on the previous chapter by showing how to build rich forms and how to use Aurelia’s flexible and powerful validation mechanism. It also explores different edition models, such as inline edition or dialog-based edition.
Chapter 5, Making Reusable Components, shows you how to build reusable Aurelia components, such as custom HTML elements and attributes. It also explains how to leverage some cutting edge Web Standards supported by Aurelia, such as the Shadow DOM and content projection.
Chapter 6, Design Concerns – Organizing and Decoupling, walks you through different ways to organize and structure an Aurelia application. It also discusses various techniques to manage communication between decoupled components.
Chapter 7, Test All the Things, teaches you how to write and run automated tests for an Aurelia application, with both unit and end-to-end tests.
Chapter 8, Internationalization, shows you how to internationalize texts and the format of various data types, such as dates and numbers.
Chapter 9, Animations, teaches you how to animate view transitions using CSS, and introduces the general animation API, so you can use richer animation plugins.
Chapter 10, Bundling for Production, shows you how to optimize for production by packaging your application in one or multiple bundles.
Chapter 11, Integrating with Other Libraries, gives examples of how you can integrate various UI libraries into your application, such as Bootstrap widgets, jQuery UI, D3, and Polymer components.
Appendix A, Using JSPM, shows you how to develop, build, and bundle an Aurelia application using SystemJS and JSPM.
Appendix B, Using Webpack, shows you how to develop, build, and bundle an Aurelia application using Webpack.
For maximum enjoyment, you will need a PC/laptop running Windows, Linux, or Mac OS X, an Internet connection, and a modern browser. All the code samples were developed and tested using Google Chrome; as such, it is the recommended browser.
All software mentioned in this book is free of charge and can be downloaded from the Internet.
This book is for all developers, either keen to learn to build single-page applications using Aurelia, or simply curious about the framework. Some knowledge of JavaScript is ideal to follow the book; however, if you’re new to JS, you’ll pick up most of the basics along the way.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "As such, in the aurelia_project/aurelia.json file, in the build section, under bundles, let's add the following entries to the dependencies of the bundle named vendor-bundle.js:"
A block of code is set as follows:
{ "name": "aurelia-i18n", "path": "../node_modules/aurelia-i18n/dist/amd", "main": "aurelia-i18n" }, { "name": "i18next", "path": "../node_modules/i18next/dist/umd", "main": "i18next" }, { "name": "i18next-xhr-backend", "path": "../node_modules/i18next-xhr-backend/dist/umd", "main": "i18nextXHRBackend" },When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<template> <h1 t="404.title"></h1> <p t="404.explanation"></p> </template>Any command-line input or output is written as follows:
> npm install aurelia-i18n i18next --saveNew terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "At this point, if you run the application, click the New button and, for example, put gibberish in the Birthday textbox then try to save."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
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/Learning-Aurelia. 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.
Developer experience is a key strength of Aurelia. Its authors paid careful attention to every aspect of the development process, so using the framework is seamless and fluid, and so the learning curve is as smooth as possible.
This book humbly attempts to follow the same philosophy. It will teach you how you can use Aurelia to build real-world applications from A to Z. In fact, while reading the book and following the code samples, that's exactly what you will do. You will start by setting up your development environment and creating the project, then I will walk you through concepts such as routing, templating, data binding, automated testing, internationalization, and bundling. We will discuss application design, communication between components, and integration of third parties. We will cover every topic most modern, real-world single-page applications require.
In this first chapter, we will start by defining some terms that will be used throughout the book. We will quickly cover some core Aurelia concepts. Then we will take a look at the core Aurelia libraries and see how they interact with each other to form a complete, full-featured framework. We will see also what tools are needed to develop an Aurelia application and how to install them. Finally, we will start creating our application and explore its global structure.
As this book is about a JavaScript framework, JavaScript plays a central role in it. If you are not completely up-to-date with the terminology, which has changed a lot in the last few years, let me clear a few things up.
JavaScript (or JS) is a dialect, or implementation, of the ECMAScript (ES) standard. It is not the only implementation, but it is definitely the most popular. In this book, I will use the JS acronym to talk about actual JavaScript code or code files and the ES acronym when talking about an actual version of the ECMAScript standard.
Like everything in computer programing, the ECMAScript standard evolves over time. At the time of writing, the latest version is ES2016 and was published in June 2016. It was originally called ES7, but TC39, the committee drafting the specification, decided to change their approval and naming model, hence the new name.
The previous version, named ES2015 (ES6) before the naming model changed, was published in June 2015 and was a big step forward as compared to the version before it. This older version, named ES5, was published in 2009 and was the most recent version for six years, so it is now widely supported by all modern browsers. If you have been writing JavaScript in the last five years, you should be familiar with ES5.
When they decided to change the ES naming model, the TC39 committee also chose to change the specification's approval model. This decision was made in an effort to publish new versions of the language at a quicker pace. As such, new features are being drafted and discussed by the community, and must pass through an approval process. Each year, a new version of the specification will be released, comprising the features that were approved during the year.
Those upcoming features are often referred as ESNext. This term encompasses language features that are approved or at least pretty close to approval but not yet published. It can be reasonable to expect that most or at least some of those features will be published in the next language version.
As ES2015 and ES2016 are still recent versions, they are not fully supported by most browsers. Moreover, ESNext features have typically no browser support at all.
Those multiple names can be pretty confusing. To make things simpler, I will stick with the official names ES5 for the previous version, ES2016 for the current version and ESNext for the next version. But that's only my preference; in the following chapters, we may encounter some tools or libraries still using the original nomenclature.
Before going any further, you should make yourself familiar with the features introduced by ES2016 and with ESNext decorators, if you are not already. We will use these features throughout the book.
If you don't know where to start with ES2015 and ES2016, you can find a great overview of the new features on Babel's website:
https://babeljs.io/docs/learn-es2015/
As for ESNext decorators, Addy Osmani, a Google engineer, explained them pretty well:
https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841
For further reading, you can take a look at the feature proposals (decorators, class property declarations, async functions, and so on) for future ES versions:
https://github.com/tc39/proposals
Before we start getting our hands dirty, there are a couple of core concepts that need to be explained.
First, Aurelia relies a lot on conventions. Most of those conventions are configurable, and can be changed if they don't suit your needs. Each time we'll encounter a convention throughout the book, we will see how to change it whenever possible.
Components are a first class citizen of Aurelia. What is an Aurelia component? It is a pair made of an HTML template, called the view, and a JavaScript class, called the view-model. The view is responsible for displaying the component, while the view-model controls its data and behavior. Typically, the view sits in an .html file and the view-model in a .js file. By convention, those two files are bound through a naming rule, they must be in the same directory and have the same name (except for their extension, of course).
Here's an example of an empty component with no data, no behavior, and a static template:
component.js
export class MyComponent {}component.html
<template> <p>My component</p> </template>A component must comply with two constraints, a view's root HTML element must be the template element, and the view-model class must be exported from the .js file. As a rule of thumb, the only function that should be exported by a component's JS file should be the view-model class. If multiple classes or functions are exported, Aurelia will iterate on the file's exported functions and classes and will use the first it finds as the view-model. However, since the enumeration order of an object's keys is not deterministic as per the ES specification, nothing guarantees that the exports will be iterated in the same order they were declared, so Aurelia may pick the wrong class as the component's view-model.
The only exception to that rule is some view resources which we'll see in Chapter 3, Displaying Data, and Chapter 5, Making Reusable Components. In addition to its view-model class, a component's JS file can export things like value converters, binding behaviors, and custom attributes basically any view resource that can't have a view, which excludes custom elements.
Components are the main building blocks of an Aurelia application. Components can use other components; they can be composed to form bigger or more complex components. Thanks to the slot mechanism, you can design a component's template so parts of it can be replaced or customized. We will see all of this in the next chapters.
Aurelia is not your average monolithic framework. It is a set of loosely coupled libraries with well-defined abstractions. Each of its core libraries solves a specific and well-defined problem common to single-page applications. Aurelia leverages dependency injection and a plugin architecture so you can discard parts of the framework and replace them with third-party or even your own implementations. Or you can just throw away features you don't need so your application is lighter and faster to load. We will look deeper into this plugin mechanism in Chapter 2, Layout, Menu, and Getting Familiar.
The core Aurelia libraries can be divided into multiple categories. Let's have a quick glance.
The following libraries are mostly independent and can be used by themselves if needed. They each provide a focused set of features and are at the core of Aurelia:
The following libraries mostly define interfaces and abstractions in order to decouple concerns and enable extensibility and pluggable behaviors. This does not mean that some of the libraries in the previous section do not expose their own abstractions besides their features. Some of them do. But the libraries described in the current section have almost no other purpose than defining abstractions:
The following libraries are the default implementations of abstractions exposed by libraries from the two previous sections:
The following libraries' purpose is to integrate some of the core libraries together. They provide interface implementations and adapters, along with default configuration or behaviors:
If you take a look at Aurelia's organization page on GitHub at https://github.com/aurelia, you will see many more repositories. The libraries listed in the previous sections are just the core of Aurelia - the tip of the iceberg, if I may. Many other libraries exposing additional features or integrating third-party libraries are available on GitHub, some of them developed and maintained by the Aurelia team, many others by the community. We'll cover some of those additional libraries in further chapters, but I strongly suggest that you explore the Aurelia ecosystem by yourself after reading this book, as it is rapidly growing, and the Aurelia community is doing some very exciting things.
In the following section, we will go over the tools needed to develop our Aurelia application.
Aurelia being a JavaScript framework, it just makes sense that its development tools are also in JavaScript. This means that the first thing you need to do when getting started with Aurelia is to install Node.js and NPM on your development environment.
Node.js is a server-side runtime environment based on Google's V8 JavaScript engine. It can be used to build complete websites or web APIs, but it is also used by a lot of front-end projects for development and to build tasks, such as transpiling, linting, and minimizing.
NPM is the de facto package manager for Node.js. It uses http://www.npmjs.com as its main repository, where all available packages are stored. It is bundled with Node.js, so if you install Node.js on your computer, NPM will also be installed.
To install Node.js and NPM on your development environment, you simply need to go to https://nodejs.org/ and download the proper installer for your environment.
If Node.js and NPM are already installed, I strongly recommend that you make sure to use at least version 3 of NPM, as older versions may have issues collaborating with some of the other tools we'll use. If you are not sure which version you have, you can check it by running the following command in a console:
> npm -vIf Node.js and NPM are already installed but you need to upgrade NPM, you can do so by running the following command:
> npm install npm -gEven though an Aurelia application can be built using any package manager, build system, or bundler you want, the preferred tool to manage an Aurelia project is the command line interface, a.k.a. the CLI.
At the time of writing, the CLI only supports NPM as its package manager and requirejs as its module loader and bundler, probably because they are both the most mature and stable. It also uses Gulp 4 behind the scenes as its build system.
CLI-based applications are always bundled when running, even in development environments. This means that the performance of an application during development will be very close to what it should be like in production. This also means that bundling is a recurring concern, as new external libraries must be added to some bundles in order to be available at runtime. We'll see this in detail in Chapter 10, Bundling for Production.
In this book, we'll stick with the preferred solution and use the CLI. There are, however, two appendices at the end of the book covering alternatives, a first for Webpack, and a second for SystemJS with JSPM.
The CLI being a command line tool, it should be installed globally, by opening a console and executing the following command:
> npm install -g aurelia-cliYou may have to run this command with administrator privileges, depending on your environment.
If you already have it installed, make sure you have the latest version, by running the following command:
> au -vYou can then compare the version this command outputs with the latest version number tagged on GitHub, at https://github.com/aurelia/cli/releases/latest.
If you don't have the latest version, you can simply update it by running the following command:
> npm install -g aurelia-cliIf for some reason the command to update the CLI fails, simply uninstall then reinstall it:
> npm uninstall aurelia-cli -g> npm install aurelia-cli -gThis should reinstall the latest version.
Getting started with Aurelia is very easy, thanks to the CLI. Installing the tooling and creating an empty project is simply a matter of running a couple of commands, and it takes typically more time waiting for the initial NPM install to complete than doing the actual setup.
In the next chapter, we'll go over dependency injection and logging, and we'll start building our application by adding components and configuring routes to navigate between them.
