70,79 €
Learn how to create mobile and full-stack web applications in JavaScript by getting a deeper insight into Meteor
If you are a web developer who is familiar with Meteor and has basic knowledge of web development, and you now want to explore new paradigms of single-page, real-time applications, this course is perfectly suited for you.
Meteor is best JavaScript development platform and is packed with collections of libraries and packages bound together in a tidy way to take care of everything from development to production, making your web development easier.
This course follows a learning path divided into three modules. Each module is a mini course in its own right, taking your knowledge to a new level as you progress. The first module takes you from the installation of Meteor to building a fully working web blog (including back end) to create and edit posts. Your path will begin with the basic concepts and folder structure of a Meteor project, learning how Meteor templates work to test packages, and seeing the application itself.
The second module is a cookbook that starts with simple recipes designed for quick reference, and culminating advanced recipes that walk you through building and deploying a complete application. The cookbook covers all the major areas of Meteor development, including lesser-known and undocumented features too.
With all the important concepts covered in the previous modules, the third module will get you equipped with simple solutions to boost your development skills. You'll learn about mapping of real-world data and optimizing it, how to optimize and secure web applications and how to deploy and maintain it without breaking its features. Throughout the module, you will put your skills into practice and build an online shop from scratch.
This Learning Path combines some of the best that Packt has to offer in one complete, curated package. It includes content from the following Packt products:
This practical handbook has a step-by-step approach to help you improve your developer skills and efficiently built web applications using Meteor.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 723
Veröffentlichungsjahr: 2016
Learn how to create mobile and full-stack web applications in JavaScript by getting a deeper insight into Meteor
A course in three modules
BIRMINGHAM - MUMBAI
Copyright © 2016 Packt Publishing
All rights reserved. No part of this course 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 course to ensure the accuracy of the information presented. However, the information contained in this course 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 course.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this course by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Published on: November 2016
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78728-775-4
www.packtpub.com
Authors
Fabian Vogelsteller
Isaac Strack
Marcelo Reyna
Reviewers
Riccardo Mancinelli
Rohit Mukherjee
Isaac Strack
Jebin B V
Ryan Wilcox
Brad Cypert
David Ryan Speer
Content Development Editor
Onkar Wani
Graphics
Abhinash Sahu
Production Coordinator
Shraddha Falebhai
Meteor is the weapon of choice for start-ups in today’s world as it’s an incredibly powerful and fun platform that allows you to build real-time web applications quickly and easily and in pure JavaScript. It provides developers with tools and flexibility to build a fully-fledged production app.
Meteor aims to create single-page applications where real time is the default. It takes care of the data synchronization and updating of the DOM. If data changes, your screen will be updated. These two basic concepts make up a lot of the work we do as web developers, and with Meteor this happens without any extra line of code.
It is modular and declarative, supports data-on-the-wire, is well supported by a thriving development community, and implements full-stack reactivity to create a great impact on your day-to-day development efforts.
As Meteor is modular and well supported, it works easily with all of your favorite JavaScript frameworks. You can use the entire Meteor stack, or you can mix and match it with community packages to complement your existing infrastructure / skill set.
Module 1, Building Single-page Web Apps with Meteor, This module takes you from the installation of Meteor to building a fully working web blog. You will start with the basic concepts and folder structure of a Meteor project, learning how Meteor templates work. Learn how to retrieve and send data to the server and manipulate the database content. Routing will later make your example app look and behave like a real website. Also, you’ll get to grips with Meteor’s reactivity concept that can rerun functions when data changes while you’re building your own reactive object, and package it later for drop-in use. After your app is ready, you will learn about ways of deploying your app on different types of servers. Finally, we will take a look at testing packages and the applications.
Module 2, Meteor Cookbook, This module starts with simple recipes designed for quick reference, and culminating in advanced recipes that walk you through building and deploying a complete application, it covers all the major areas of Meteor development, including lesser-known and undocumented features. You will have instant access to step-by-step recipes, accompanied by clear, concise explanations on optimizing your workflow.
Module 3, Meteor Design Patterns, Module starts off with a refresher on the basics of JavaScript programming such as templates, CoffeeScript, the Event Loop, and the Merge Box, amongst others. You then learn how to map real-world data and optimize the data’s publishers to output data with the least amount of work done by the server with some subscribe and publish patterns. Following this, you will see how to optimize and secure the web application and maintain applications without breaking other features. Finally, you will learn how to deploy a secure production-ready application while learning to set up modulus, compose with Oplog tracking and SSL certificates, as well as error tracking with Kadira.
Module 1:
To follow the examples in the modules, you will need a text editor to write the code. It’s highly recommended to use Sublime Text as your IDE, as it has a wide range of plugins for almost every task a web developer could think of.
You will also need a modern browser to see your results. As many examples use the browser console to make changes to the database and to see the results of the code snippets, I recommend Google Chrome. Its Developer tools web inspector has everything a web developer needs to work and debug websites with ease.
Additionally, you can use Git and GitHub to store your success every step along the way and in order to go back to the previous versions of your code.
The code examples for each chapter will also be available on GitHub at
https://github.com/frozeman/book-building-single-page-web-apps-with-meteor, where each commit in this repository correlates with one chapter of the module, giving you an easy way to see what was added and removed in each step along the way
Module 2:
This module assumes that you have a working knowledge of JavaScript and HTML. Being familiar with Node, npm, GitHub and the command line/terminal will be very helpful (but not critical) to getting the most out of the recipes in this book.
You will find recipes to install Meteor on Mac OS X or Linux, with links to using Meteor on Windows and Google Chromebooks. In every instance, you will need access to the Internet to download Meteor and community packages, and you will need installation privileges for your developer machine regardless of the operating system.
For deployment to production environments or to mobile devices, the requirements will vary from recipe to recipe. To complete all of the recipes successfully, you will need your own hosted server and DNS domain as well as iOS, Android, or Windows mobile devices and SDKs.
Module 3:
• Meteor version 1.1.0.2 or above
• A Unix system such as a Mac or Linux computer
If you are a web developer who is familiar with Meteor and has basic knowledge of web development, and you now want to explore new paradigms of single-page, real-time applications, this course is perfectly suited for you.
Feedback from our readers is always welcome. Let us know what you think about this course—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 course’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 course, 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 course from your account at http://www.packtpub.com. If you purchased this course 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 course’s webpage at the Packt Publishing website. This page can be accessed by entering the course’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 course is also hosted on GitHub at https://github.com/ PacktPublishing/Meteor-Full-Stack-Web-Application-Development. We also have other code bundles from our rich catalog of books, videos, and courses 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 courses—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 course. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your course, 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 course 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 course, you can contact us at <[email protected]>, and we will do our best to address the problem.
Building Single-page Web Apps with Meteor
Build real-time apps at lightning speed using the most powerful full-stack JavaScript framework
Welcome to this book on Meteor. Meteor is an exciting new JavaScript framework, and we will soon see how easy it is to achieve real and impressive results with less code.
In this chapter, we will learn what the requirements are and what additional tools we need to get started. We will see how simple it is to get our first Meteor application running and what a good basic folder structure for a Meteor app could be. We will also learn about Meteor's automatic build process and its specific way of loading files.
We will also see how to add packages using Meteors official packaging system. At the end of the chapter, we will take a short look at Meteor's command-line tool and some of its functions.
To bring it together, we will cover the following topics:
Meteor is not just a JavaScript library such as jQuery or AngularJS. It's a full-stack solution that contain frontend libraries, a Node.js-based server, and a command-line tool. All this together lets us write large-scale web applications in JavaScript, on both the server and client, using a consistent API.
Even with Meteor being quite young, already a few companies such as https://lookback.io, https://respond.ly, and https://madeye.io use Meteor in their production environment.
If you want to see for yourself what's made with Meteor, take a look at http://madewith.meteor.com.
Meteor makes it easy for us to build web applications quickly and takes care of the boring processes such as file linking, minifying, and concatenating of files.
Here are a few highlights of what is possible with Meteor:
With Meteor, we never have to link files with the <script> tags in HTML. Meteor's command-line tool automatically collects JavaScript or CSS files in our application's folder and links them in the index.html file, which is served to clients on initial page load. This makes structuring our code in separate files as easy as creating them.
Meteor's command-line tool also watches all files inside our application's folder for changes and rebuilds them on the fly when they change.
Additionally, it starts a Meteor server that serves the app's files to the clients. When a file changes, Meteor reloads the site of every client while preserving its state. This is called a hot code reload.
In production, the build process also concatenates and minifies our CSS and JavaScript files.
By simply adding the less and coffee core packages, we can even write all styles in LESS and code in CoffeeScript with no extra effort.
The command-line tool is also the tool for deploying and bundling our app so that we can run it on a remote server.
Sounds awesome? Let's take a look at what's needed to use Meteor.
Meteor is not just a JavaScript framework and server. As we saw earlier, it is also a command-line tool that has a whole build process for us in place.
Currently, the operating systems that are officially supported are as follows:
The Windows installer is still in development at the time of writing this book. Please follow the wiki page at https://github.com/meteor/meteor/wiki/Preview-of-Meteor-on-Windows.
This book and all examples use Meteor 1.0.
We will also need Google Chrome or Firefox with the Firebug add-on installed to follow examples that require a console. The examples, screenshots, and explanations in this book will use Google Chrome's developer tools.
I highly recommend using GitHub when working with web projects, such as the one we will work on in this book. Git and GitHub help us to back up our progress and let us always go back to previous states while seeing what we've changed.
Git is a version control system, which was created in 2005 by the inventor of Linux, Linus Torvalds.
With Git, we can commit any state of our code and later go back to that exact state. It also allows multiple developers to work on the same code base and merge their results together in an automated process. If conflicts appear in this process, the merging developer is able to resolve those merge conflicts by removing the unwanted lines of code.
I also recommend registering an account at http://github.com, as this is the easiest way to browse our code history. They have an easy to use interface as well as a great Windows and Mac app.
To follow the code examples in this book, you can download all code examples for each chapter from the book's web page at https://www.packtpub.com/books/content/support/17713.
Additionally, you will be able to clone the book's code from http://github.com/frozeman/book-building-single-page-web-apps-with-meteor. Every tag in this repository equals to one chapter of the book and the commit history will help you to see the changes, which were made in each chapter.
Installing Meteor is as easy as running the following command in the terminal:
That's it! This will install the Meteor command-line tool ($ meteor), the Meteor server, MongoDB database, and the Meteor core packages (libraries).
All command-line examples are run and tested on Mac OS X and can differ on Linux or Windows systems.
To install Git, I recommend installing the GitHub app from https://mac.github.com or https://windows.github.com. We can then simply go inside the app to Preferences and click on the Install Command Line Tools button inside the Advanced tab.
If we want to install Git manually and set it up via the command line, we can download the Git installer from http://git-scm.com and follow this great guide at https://help.github.com/articles/set-up-git.
Now, we can check whether everything was installed successfully by opening the terminal and running the following command:
Downloading the example code
You can download the example code files for all Packt books you have purchased 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.
This should return us a list of Git options. If we get command not found: git, we need to check whether the git binary was correctly added to our PATH environment variable.
If everything is fine, we are ready to create our first Meteor app.
To create our first app, we open the terminal, go to the folder where we want to create our new project, and enter the following commands:
Meteor will now create a folder named my-meteor-blog. The HTML, CSS, and JavaScript files that Meteor created for us inside this folder are already a fully working Meteor app. To see it in action, run the following commands:
Meteor will now start a local server for us on port 3000. Now, we can open our web browser and navigate to http://localhost:3000. We will see the app running.
This app doesn't do much, except showing a simple reactive example. If you click on the Click Me button, it will increase the counter:
For later examples, we will need Google Chrome's developer tools. To open the console, we can press Alt + command + I on Mac OS X or click on the menu button on the upper-right corner of Chrome, select More tools, and then Developer tools.
The Developer tools allow us to inspect the DOM and CSS of our website, as well as having a console where we can interact with our website's JavaScript.
For this book, we will build our own app from scratch. This also means we have to set up a sustainable folder structure, which helps us to keep our code organized.
With Meteor, we are very flexible concerning our folder structure. This means we can put our files wherever we want, as long as they are inside the app's folder. Meteor treats specific folders differently, allowing us to expose files only on the client, the server, or both. We will take a look at those specific folders later.
But, first let's get our hands dirty by deleting all preadd files in our newly created application folder and creating the following folder structure:
To fully focus on the Meteor code but still have a pretty-looking blog, I strongly recommend to download the code that accompanies this chapter from the book's web page at http://packtpub.com/books/content/support/17713. They will contain already two drop-in-place style files (lesshat.import.less and styles.less), which will let your example blog look pretty in the upcoming chapters.
You can also download these files directly from GitHub at https://github.com/frozeman/book-building-single-page-web-apps-with-meteor/tree/chapter1/my-meteor-blog/client/styles and copy them to the my-meteor-blog/client/styles folder manually.
Next, we need to add some basic packages so that we can start building our app.
Packages in Meteor are libraries that can be added to our projects. The nice thing about Meteor packages is that they are self-contained units, which run out of the box. They mostly add either some templating functionality or provide extra objects in the global namespace of our project.
Packages can also add features to Meteor's build process such as the stylus package, which lets us write our app's style files with the stylus preprocessor syntax.
For our blog, we will need two packages at first:
less: This is a Meteor core package and will compile our style files on the fly to CSS
jeeeyul:moment-with-langs: This is a third-party library for date parsing and formatting
To add the less package, we can simply open the terminal, go to our projects folder, and enter the following command:
Now, we are able to use any *.less files in our project, and Meteor will automatically compile them in its build process for us.
To add a third-party package, we can simply search for packages on either https://atmospherejs.com, which is the frontend for Meteors packaging system, or use the command-line tool, $ meteor search <package name>.
For our blog, we will need the jeeeyul:moment-with-langs package that allows us later to simply manipulate and format dates.
Packages are namespaced with the authors name followed by a colon.
To add the moment package, we simply enter the following command:
After the process is done, and we restarted our app using $ meteor, we will have the moment object available in our app global namespace and we can make use of it in the upcoming chapters.
Should we ever want to add only specific version of a package, we can use the following command:
If you want a version in the 1.0.0 (but not the 2.0.0) range use the following command:
To update only packages we can simply run the following command:
Additionally, we can update only a specific package using the following command:
That's it! Now we are fully ready to start creating our first templates. You can jump right into the next chapter, but make sure you come back to read on, as we will now talk about Meteor's build process in more detail.
Now that we know already about Meteor's build process and folder structure, we will take a closer look at what we can do with the command-line tool that Meteor provides.
As we saw when using the meteor command, we need to be inside a Meteor project so that all actions will be performed on this project. For example, when we run meteor add xxx, we add a package to the project where we are currently in.
If Meteor releases a new version, we can simply update our project by running the following command:
If we want to go back to a previous version, we can do this by running the following command:
This would set our project back to release version 0.9.1.
Deploying our Meteor app to a public server is as easy as running the following command:
This would ask us to register a Meteor developer account and deploy our app at http://my-app-name.meteor.com.
For a full introduction on how to deploy a Meteor app, refer to Chapter 10, Deploying Our App.
In the Appendix, you can find a full list of Meteor commands and their explanations.
In this chapter, we learned what Meteor requires to run, how to create a Meteor application, and how the build process works.
We understand that Meteor's folder structure is rather flexible, but that there are special folders such as the client, server, and lib folder, which are loaded in different places and order. We also saw how to add packages and how to use the Meteor command-line tool.
If you want to dig deeper into what we've learned so far, take a look at the following parts of the Meteor documentation:
You can find this chapter's code examples at https://www.packtpub.com/books/content/support/17713 or on GitHub at https://github.com/frozeman/book-building-single-page-web-apps-with-meteor/tree/chapter1.
Now that we've set up our project's basic folder structure, we are ready to start with the fun part of Meteor—templates.
After we successfully installed Meteor and set up our folder structure, we can now start building the basic templates for our blog.
In this chapter, we will learn how templates are built. We will see how to display data and how some parts can be altered using helper functions. We will take a look on adding events, using conditions, and understanding data contexts, all in templates.
The following is an overview of what will be covered in this chapter:
If you jump right into this chapter without setting up the folder structure in the Chapter 1, Getting Started with Meteor, download the previous chapter's code examples from either the book's web page at https://www.packtpub.com/books/content/support/17713 or from the GitHub repository at https://github.com/frozeman/book-building-single-page-web-apps-with-meteor/tree/chapter1.
These code examples will also contain all the style files, so we don't have to worry about adding CSS code along the way.
Normally when we build websites, we build the complete HTML on the server side. This was quite straightforward; every page is built on the server, then it is sent to the client, and at last JavaScript added some additional animation or dynamic behavior to it.
This is not so in single-page apps, where every page needs to be already in the client's browser so that it can be shown at will. Meteor solves this problem by providing templates that exists in JavaScript and can be placed in the DOM at some point. These templates can have nested templates, allowing for an easy way to reuse and structure an app's HTML layout.
Since Meteor is so flexible in terms of folder and file structure, any *.html page can contain a template and will be parsed during Meteor's build process. This allows us to put all templates in the my-meteor-blog/client/templates folder, which we created in the Chapter 1, Getting Started with Meteor. This folder structure is chosen as it helps us organizing templates when our app grows.
Meteor's template engine is called Spacebars, which is a derivative of the handlebars template engine. Spacebars is built on top of Blaze, which is Meteor's reactive DOM update engine.
Blaze can generate reactive HTML directly using its API, though it's more convenient to use Meteor's Spacebars or a third-party template language built on top of Blaze such as Jade for Meteor.
For more detail about Blaze, visit https://docs.meteor.com/#/full/blaze and https://github.com/mquandalle/meteor-jade.
What makes Spacebars so exciting is its simplicity and reactivity. Reactive templates mean that some parts of the template can automatically change when the underlying data changes. There is no need of manual DOM manipulation and inconsistent interfaces belong to the past. To get a better understanding of Meteor, we will start with the basic HTML files for our app:
Note that our index.html file doesn't contain the <html>...</html> tags, as Meteor gathers all <head> and <body> tags in any file and builds up its own index.html file, which will be delivered to the user. Actually, we can also name this file myapp.html.
This will start a Meteor server with our app running.
That's it! We can open our browser, navigate to http://localhost:3000, and we should see Hello World.What happens here is that Meteor will look through all the HTML files available in our app's folder, concatenating the content of all <head> and <body> tags, which it finds and serve them to the clients as its index file.
If we take a look at the source code of our app, we will see that the <body> tag is empty. This is because Meteor sees the content of the <body> tag as its own templates, which will be injected with its corresponding JavaScript template when the DOM is loaded.
To see the source code, don't use the Developer Tools' elements panel, as this will show us the source code after the JavaScript is executed. Right-click on the website instead and select View page source in Chrome.
We will also see that Meteor already linked all kinds of JavaScript files in our <head> tag. These are Meteor's core packages and our add third-party packages. In production, these files will be concatenated into one. To see this in action, go to the terminal, quit our running Meteor server using Ctrl + C, and run the following command:
If we now take a look at the source code, we will see that there is only one cryptic-looking JavaScript file linked.
For the next steps, it is better to go back to our developer mode by simply quitting Meteor and running the meteor command again, since this will reload the app faster when file changes occur.
Now, let's add the basic templates to our blog by creating a file called layout.html in the my-meteor-blog/client/templates folder. This template will serve as the wrapper template for our blog layout. To build the basic templates, perform the following steps:
As you can see, we used a {{#markdown}} block helper to wrap our texts. The curly braces are handlebars syntax, which Blaze uses to bring logic to the HTML. The {{#markdown}}...{{/markdown}} block will transform all markdown syntax inside into HTML when the template gets rendered.
The markdown text cannot be indented as we do with the HTML tags because the markdown syntax interprets indentation as code.
However, when we now go to our browser, we will still see Hello World. So how can we make now our templates visible?
To show the home template in the app, we need to open index.html, which we created earlier, and perform the following steps:
If we would now switch {{> home}} for {{> about}}, we would see our about template instead.
Now that we've seen how we can display data using a helper, let's see how we can set the whole data context of a template:
This will show the text in the contextExample template because we were displaying it using {{someText}}.
Remember that filenames don't really matter as Meteor is collecting and concatenating them anyway; however, the template name matters since we use this to reference templates.
Setting the context in HTML is not very dynamic, as it is hardcoded. To be able to dynamically change the context, it is better to set it using a template helper function.
To do this, we must first add the helper to our home templates helpers, which returns the data context, as follows:This will now display both the someText and the someNested.text, which was returned by our helper functions.
Another way of setting the data context is by using the {{#with}} block helper. The following code snippet has the same result as the former inclusion helper that utilizes the helper function:
We would even get the same results in the browser when we don't use a subtemplate and just add the content of the contextExample template inside the {{#with}} block helper, as follows:
To make our template a bit more dynamic, we will add a simple event, which will reactively rerun the logContext helper we created earlier.
First, however, we need to add a button to our contextExample template:
To catch the click event, open examples.js and add the following event function:
This will set a session variable called randomNumber to a random number.
We will talk in depth about sessions in the next chapter. For now, we only need to know that when a session variable changes, all functions that get that session variable using Session.get('myVariable') will run again.
To see this in action, we will add a Session.get() call to the logContext helper, and return the former set's random number as follows:
If we go to the browser, we will see the Get some random number
