Meteor: Full-Stack Web Application Development - Fabian Vogelsteller - E-Book

Meteor: Full-Stack Web Application Development E-Book

Fabian Vogelsteller

0,0
70,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn how to create mobile and full-stack web applications in JavaScript by getting a deeper insight into Meteor

About This Book

  • This step-by-step tutorial will show you how to build fast, complex web applications
  • Over 65 hands-on recipes help you build and deploy elegant web applications
  • Optimize your web application for production use

Who This Book Is For

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.

What You Will Learn

  • Secure your site with Meteor best practices
  • Create reactive templates that update themselves when data changes
  • Add routing to a single-page application and make it appear like a real website
  • Make your own Meteor packages and see how to make them public
  • Rapidly build robust, responsive user interfaces
  • Publish your own reusable custom packages
  • Optimize your site for load speed with advanced publishers and subscribers
  • Master the intricacies of front-end development using Jeet, Bootstrap, CSS animations, and more
  • Leverage the aggregation framework to produce results with big data
  • Optimize your site for search engine visibility

In Detail

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:

  • Building Single-page Web Apps with Meteor, Fabian Vogelsteller
  • Meteor Cookbook, Isaac Strack
  • Meteor Design Patterns, Marcelo Reyna

Style and approach

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 723

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Meteor: Full-Stack Web Application Development
Meteor: Full-Stack Web Application Development
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
I. Module 1
1. Getting Started with Meteor
The full-stack framework of Meteor
Meteor's requirements
Using Chrome's developer tools
Using Git and GitHub
Installing Meteor
Installing Git
Creating our first app
Creating a good folder structure
Preadd style files
Adding basic packages
Adding a core package
Adding a third-party package
Variable scopes
Meteor's folder conventions and loading order
Loading assets on the server
Meteor's command-line tool
Updating Meteor
Deploying Meteor
Summary
2. Building HTML Templates
Writing templates in Meteor
Building the basic templates
Adding templates and partials
Displaying data with template helpers
Setting the data context for a template
Using the {{#with}} block helper
"this" in template helpers and template callbacks
Adding events
Block helpers
Listing posts
Spacebars syntax
Accessing parent data contexts
Passing data to helpers
Summary
3. Storing Data and Handling Collections
Meteor and databases
Setting up a collection
Adding post examples
Querying a collection
Updating a collection
Database everywhere
Differences between client and server collections
Summary
4. Controlling the Data Flow
Syncing data – the current Web versus the new Web
Removing the autopublish package
Publishing data
Publishing only parts of data
Publishing specific fields
Lazy loading posts
Switching subscriptions
Some notes on data publishing
Summary
5. Making Our App Versatile with Routing
Adding the iron:router package
Setting up the router
Switching to a layout template
Adding another route
Moving the posts subscription to the Home route
Setting up the post route
Creating a single-post publication
Adding the post route
Linking the posts
Changing the website's title
Summary
6. Keeping States with Sessions
Meteor's session object
A better way for simple reactivity
Using sessions in template helpers
Session and hot code pushes
Rerunning functions reactively
Stopping reactive functions
Using autorun in a template
The reactive session object
Summary
7. Users and Permissions
Meteor's accounts packages
Adding the accounts packages
Adding admin functionality to our templates
Adding a link for new posts
Adding the link to edit posts
Adding the login form
Creating the template to edit posts
Creating the admin user
Adding permissions
A note on security
Creating routes for the admin
Preventing visitors from seeing the admin routes
Summary
8. Security with the Allow and Deny Rules
Adding a function to generate slugs
Creating a new post
Saving a post
Editing posts
Updating the current post
Restricting database updates
Removing the insecure package
Adding our first allow rules
Adding a deny rule
Adding posts using a method call
Method stubs and latency compensation
Changing the button
Adding the method
Calling the method
Summary
9. Advanced Reactivity
Reactive programming
The invalidating cycle
Building a simple reactive object
Rerunning functions
Creating an advanced timer object
Reactive computations
Stopping reactive functions
Preventing run at start
Advanced reactive objects
Summary
10. Deploying Our App
Deploying on meteor.com
Deploying on meteor.com using a domain name
Backup and restore databases hosted on meteor.com
Deploying on other servers
Bundling our app
Deploying using Demeteorizer
Deploying using Meteor Up
Setting up the server
Deploying with mup
Outlook
Summary
11. Building Our Own Package
The structure of a package
Creating our own package
Adding the package metadata
Adding the package
Releasing our package to the public
Publishing our package online
Updating our package
Summary
12. Testing in Meteor
Types of tests
Testing packages
Adding package tests
Running the package tests
Testing our meteor app
Testing using Jasmine
Adding unit tests to the server
Adding integration tests to the client
Adding a test for the visitors
Adding a test for the admin
Acceptance tests
Nightwatch
Laika
Summary
A. Appendix
List of Meteor's command-line tool commands
The iron:router hooks
II. Module 2
1. Optimizing Your Workflow
Introduction
Installing Meteor
Getting ready
How to do it...
How it works...
There's more...
Finding documentation for Meteor
How to do it…
How it works…
There's more…
Getting help with questions
How to do it…
How it works…
Stack Overflow
Meteor forums
The #meteor on IRC
There's more…
Setting up your project file structure
Getting ready
How to do it…
How it works…
client/server
main/lib
public/private
both
There's more…
See also
Setting up your development environment
Getting ready?
How to do it…
How it works…
There's more…
See also
Using the web console
Getting ready
Safari
Firefox
Chrome
How to do it…
How it works…
There's more…
Deploying a test app to Meteor
Getting ready
How to do it…
How it works…
There's more…
See also
Deploying to Meteor using a CNAME redirect
Getting ready
How to do it…
How it works…
See also
Deploying to a custom hosted environment
Getting ready
How to do it…
How it works…
There's more…
See also
Deploying with Meteor Up (MUP)
Getting ready
How to do it…
How it works…
See also
Using CoffeeScript
Getting ready
How to do it…
How it works…
See also
Using CSS compilers
Getting ready
How to do it…
Using Stylus
Using Less
Using SCSS / SASS
How it works…
See also
2. Customizing with Packages
Introduction
Adding Meteor packages
Getting ready
How to do it...
How it works...
There's more…
See also
Removing Meteor packages
Getting ready
How to do it…
How it works…
There's more…
Discovering new packages with Atmosphere
Getting ready
How to do it…
How it works…
There's more…
See also
Creating a multipage application with Iron Router
Getting ready
How to do it…
How it works…
There's more…
See also
Building a custom package
Getting ready
How to do it…
How it works…
There's more…
See also
Using npm modules
Getting ready
How to do it…
How it works…
There's more…
See also
Publishing custom packages to Atmosphere
Getting ready
How to do it…
How it works…
There's more…
See also
3. Building Great User Interfaces
Introduction
Inserting templates with Spacebars
Getting ready
How to do it...
How it works...
There's more…
Inserting raw HTML using triple braces
Getting ready
How to do it…
How it works…
See also
Creating dynamic lists
Getting ready
How to do it…
How it works…
There's more…
See also
Building a smooth interface with Bootstrap
Getting ready
How to do it…
How it works…
There's more…
See also
Creating customized global helpers
Getting ready
How to do it…
How it works…
There's more…
See also
Creating custom components
Getting ready
How to do it…
How it works…
There's more…
See also
Using reactivity with HTML attributes
Getting ready
How to do it…
How it works…
See also
Using dynamic templates
Getting ready
How to do it...
How it works…
There's more…
See also
Animating DOM elements
Getting ready
How to do it...
How it works…
There's more…
See also
4. Creating Models
Introduction
Implementing a simple collection
Getting ready
How to do it...
How it works...
See also
Using the Session object
Getting ready
How to do it…
How it works…
There's more…
See also
Sorting with MongoDB queries
Getting ready
How to do it…
How it works…
There's more…
See also
Filtering with MongoDB queries
Getting ready
How to do it…
How it works…
There's more…
See also
Creating upsert MongoDB queries
Getting ready
How to do it…
How it works…
There's more…
See also
Implementing a partial collection
Getting ready
How to do it…
How it works…
There's more…
See also
5. Implementing DDP
Introduction
Reading the DDP stream
Getting ready
How to do it...
How it works...
There's more…
See also
Using client-only collections
Getting ready
How to do it…
How it works…
See also
Implementing multiserver DDP
Getting ready
How to do it…
How it works…
There's more…
See also
Integrating DDP with other technologies
Getting ready
How to do it…
How it works…
There's more…
See also
6. Mastering Reactivity
Introduction
Creating and consuming a reactive value
Getting ready
How to do it...
How it works...
There's more…
See also
Using Ajax query results in ReactiveVar
Getting ready
How to do it…
How it works…
See also
Making a custom library reactive
Getting ready
How to do it…
How it works…
See also
Updating Blaze templates without Mongo
Getting ready
How to do it…
How it works…
See also
Using inline data to modify UI elements reactively
Getting ready
How to do it...
How it works...
There's more…
See also
Integrating a jQuery UI
Getting ready
How to do it...
How it works...
There's more…
See also
7. Using Client Methods
Introduction
Creating dynamic graphs with SVG and Ajax
Getting ready
How to do it...
How it works...
See also
Using the HTML FileReader to upload images
Getting ready
How to do it…
How it works…
There's more…
See also
Creating a coloring book with the Canvas element
Getting ready
How to do it…
How it works…
There's more…
See also
8. Integrating Third-party Libraries
Introduction
Using npm packages directly
Getting ready
How to do it...
How it works...
There's more...
See also
Building graphs with D3.js
Getting ready
How to do it…
How it works…
There's more…
See also
Creating cutting-edge UIs with Polymer
Getting ready
Creating your app and folders
Creating your files
Configuring Bower and installing Polymer
Adding helper Meteor packages
Configuring Meteor
How to do it…
How it works…
There's more…
See also
9. Securing Your Application
Introduction
Basic safety – turning off autopublish
Getting ready
Project setup
Creating a basic template
Adding CSS styling
How to do it...
How it works...
See also
Basic safety – removing insecure
Getting ready
How to do it...
How it works...
See also
Securing data transactions with allow and deny
Getting ready
How to do it...
How it works...
There's more…
See also
Hiding data with façades
Getting ready
How to do it...
How it works...
See also
Protecting the client with browser-policy
Getting ready
Scaffolding setup
Add CDN-hosted bootstrap
Add inline and eval() scripts
How to do it...
How it works...
See also
10. Working with Accounts
Introduction
Implementing OAuth accounts packages
Getting ready
How to do it...
How it works...
There's more…
See also
Customizing the accounts login
Getting ready
How to do it...
How it works...
There's more…
See also
Performing two-factor authentication
Getting ready
Creating our baseline application
Signing up for the Twilio SMS service
Creating an SMS service on Twilio
Installing the twilio-node npm package
Creating and testing the sendTwilio() method
How to do it...
How it works...
There's more…
See also
11. Leveraging Advanced Features
Introduction
Building custom server methods
Getting ready
Project setup
Creating a simple app
How to do it...
How it works...
There's more…
See also
Creating custom EJSON objects
Getting ready
Declaring the Swatch object
Modifying Swatches.insert()
Changing Swatch colors
How to do it…
How it works…
There's more…
See also
Handling asynchronous events
Getting ready
Creating a baseline Meteor app
Obtaining your Twitter Access Tokens
Initializing twit
Creating the Tweets collection, and building a stream reader
Tracking and testing changes
How to do it…
How it works…
There's more…
See also
Using asynchronous functions
Getting ready
How to do it…
How it works…
There's more…
See also
12. Creating Useful Projects
Introduction
Creating RESTful web services
Getting ready
Creating the baseline application
Installing and configuring Postman
How to do it...
How it works...
There's more…
See also
Creating a complete app with Iron Router
Getting ready
How to do it…
How it works…
There's more…
See also
Deploying apps to mobile devices
Getting ready
How to do it…
How it works…
There's more…
See also
Adding social sharing
Getting ready
How to do it…
How it works…
There's more…
See also
III. Module 3
1. Getting Started with Meteor
CoffeeScript for Meteor
Objects and arrays
Logical statements and operators
Functions
Binding
Jade for Meteor
HTML tags
Templates and components
Helpers
Stylus for Meteor
CSS tags
Variables
Functions/mixins
Templates, helpers, and events
Templates
Creating helpers
Events
The event loop and the merge box
The event loop
The merge box
The beginning of our online shop
The must-have packages
File structure
Summary
2. Publish and Subscribe Patterns
Template-level subscriptions
Setting up products for the online shop
Building the publisher
Subscribing to the publisher
Database relationships
One to one
One to many
Many to many
Publishing with relations
Publishing products with images (one to one)
Publishing orders with details (one to many)
Publishing a tag with products (many to many)
Key, foreign key, options, and filter
Aggregation publishers
The aggregation framework
Publishing the results
External API publishers
The HTTP package
Summary
3. Front-end Patterns
Responsive design
General settings
Bootstrap
Jeet grid systems with Rupture
Super helpers
Defining a Blaze helper
Making a global dictionary
Variable types
Session variables
Persistent variables
File scope variables
The ReactiveVar variables
Forms
Meteor Methods
Autoform
Loading data
Designing the loading indicator
Implementing the loading indicator
Animations and transitions
Animating with CSS
Executing animations in Meteor
SEO
Prerender.io
Using Meta
Schema.org
Summary
4. Application Patterns
Filtering and paging collections
Router gotchas
Stateful pagination
Filtering
Security
Roles
Collection2
Deny rules
Custom deny rules
The Meteor methods – round 2
Managing the wait time
Browser policy
Framing
Content
External APIs
Synchronization
Webhooks
Summary
5. Testing Patterns
Behavior tests
Unit tests
Summary
6. Deployment
Setting up Modulus
Setting up Compose
Setting up Kadira
Setting up an SSL certificate
Summary
B. Bibliography
Index

Meteor: Full-Stack Web Application Development

Meteor: Full-Stack Web Application Development

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

Meteor: Full-Stack Web Application Development

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

Credits

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

Preface

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.

What this learning path covers

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.

What you need for this learning path

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

Who this learning path is for

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.

Reader feedback

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.

Customer support

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.

Downloading the example code

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:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the course in the Search box.Select the course for which you’re looking to download the code files.Choose from the drop-down menu where you purchased this course from.Click on Code Download.

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:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

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!

Errata

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

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.-

Questions

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.

Part I. Module 1

Building Single-page Web Apps with Meteor

Build real-time apps at lightning speed using the most powerful full-stack JavaScript framework

Chapter 1. Getting Started with Meteor

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:

The full-stack framework of MeteorMeteor's requirementsInstalling MeteorAdding basic packagesMeteor's folder conventions and loading orderMeteor's command-line tool

The full-stack framework of Meteor

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:

We can build complex web applications amazingly fast using templates that automatically update themselves when data changesWe can push new code to all clients on the fly while they are using our appMeteor core packages come with a complete account solution, allowing a seamless integration of Facebook, Twitter, and moreData will automatically be synced across clients, keeping every client in the same state in almost real timeLatency compensation will make our interface appear super fast while the server response happens in the background.

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's requirements

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:

Mac OS X 10.6 and aboveLinux x86 and x86_64 systemsWindows

Note

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.

Using Chrome's developer tools

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.

Using Git and GitHub

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

Installing Meteor is as easy as running the following command in the terminal:

$ curl https://install.meteor.com/ | sh

That's it! This will install the Meteor command-line tool ($ meteor), the Meteor server, MongoDB database, and the Meteor core packages (libraries).

Note

All command-line examples are run and tested on Mac OS X and can differ on Linux or Windows systems.

Installing Git

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:

$ git

Tip

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.

Creating our first 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:

$ cd my/developer/folder$ meteor create my-meteor-blog

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:

$ cd my-meteor-blog$ meteor

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.

Creating a good folder structure

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:

- my-meteor-blog - server - client - styles - templates

Preadd style files

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.

Adding basic packages

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

Adding a core package

To add the less package, we can simply open the terminal, go to our projects folder, and enter the following command:

$ meteor add less

Now, we are able to use any *.less files in our project, and Meteor will automatically compile them in its build process for us.

Adding a third-party package

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:

$ meteor add jeeeyul:moment-with-langs

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:

$ meteor add jeeeyul:moment-with-langs@=2.8.2

If you want a version in the 1.0.0 (but not the 2.0.0) range use the following command:

$ meteor add jeeeyul:[email protected]

To update only packages we can simply run the following command:

$ meteor update –-packages-only

Additionally, we can update only a specific package using the following command:

$ meteor update jeeeyul:moment-with-langs

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.

Meteor's command-line tool

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.

Updating Meteor

If Meteor releases a new version, we can simply update our project by running the following command:

$ meteor update

If we want to go back to a previous version, we can do this by running the following command:

$ meteor update –-release 0.9.1

This would set our project back to release version 0.9.1.

Deploying Meteor

Deploying our Meteor app to a public server is as easy as running the following command:

$ meteor deploy my-app-name

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.

Summary

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:

https://www.meteor.com/projectshttps://www.meteor.com/toolhttps://docs.meteor.com/#/full/whatismeteorhttps://docs.meteor.com/#/full/structuringyourapphttps://docs.meteor.com/#/full/usingpackageshttps://docs.meteor.com/#/full/assetshttps://docs.meteor.com/#/full/commandline

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.

Chapter 2. Building HTML 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:

The basic template structureDisplaying dataWriting template helper functionsUsing conditions in templatesData contexts and how those can be setNesting templates and data context inheritanceAdding eventsBuilding block helpers

Note

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.

Writing templates in Meteor

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.

Note

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:

Let's create an index.html file in our my-meteor-blog/client folder with the following lines of code:
<head> <title>My Meteor Blog</title> </head> <body> Hello World </body>

Note

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.

Next, we run our Meteor app from the command line by typing the following command:
$ cd my-meteor-blog$ meteor

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.

Note

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:

$ meteor --production

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.

Building the basic templates

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:

Add the following lines of code to layout.html, which we just created:
<template name="layout"> <header> <div class="container"> <h1>My Meteor Single Page App</h1> <ul> <li> <a href="/">Home</a> </li> <li> <a href="/about">About</a> </li> </ul> </div> </header> <div class="container"> <main> </main> </div> </template>
Next, we will create the home page template, which will later list all our blogs posts. In the same templates folder as layout.html, we will create a file named home.html with the following lines of code:
<template name="home"> {{#markdown}} ## Welcome to my Blog Here I'm talking about my latest discoveries from the world of JavaScript. {{/markdown}} </template>
The next file will be a simple About page and we save it as about.html with the following code snippet:
<template name="about"> {{#markdown}} ## About me Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud **exercitation ullamco** laboris nisi ut aliquip ex ea commodo consequat. Link to my facebook: [facebook.com][1] [1]: http://facebook.com {{/markdown}} </template>

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.

Note

The markdown text cannot be indented as we do with the HTML tags because the markdown syntax interprets indentation as code.

To be able to use {{#markdown}} block helper, we need to first add the markdown core package to our app. To do this, we quit our running app in the terminal using Ctrl + C and type the following command:
$ meteor add markdown
Now we can run the meteor command again to start our server.

However, when we now go to our browser, we will still see Hello World. So how can we make now our templates visible?

Adding templates and partials

To show the home template in the app, we need to open index.html, which we created earlier, and perform the following steps:

We replace Hello World with the following template inclusion helper:
{{> layout}}
If we go back to our browser now, we see that the text is gone and the layout template, which we created earlier, has appeared with its header and menu.To complete the page, we need to show the home template in the layout template. We do this by simply adding another template inclusion helper to the main section of the layout template in our layout.html file, as follows:
<main> {{> home}} </main>
If we go back to the browser, we should see the following screenshot:

If we would now switch {{> home}} for {{> about}}, we would see our about template instead.

Setting the data context for a template

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:

For the next examples, we will create a file called examples.html in our my-meteor-blog/client/templates folder and add the following code snippet:
<template name="contextExample"> <p>{{someText}}</p> </template>
Now that we have our contextExample template, we can add it to our home template by passing some data as follows:
{{> contextExample someText="I was set in the parent template's helper, as an argument."}}

This will show the text in the contextExample template because we were displaying it using {{someText}}.

Tip

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:
Template.home.helpers({ // other helpers ... dataContextHelper: function(){ return { someText: 'This text was set using a helper of the parent template.', someNested: { text: 'That comes from "someNested.text"' } }; } });
Now we can add this helper as the data context to our contextExample template inclusion helper, as follows:
{{> contextExample dataContextHelper}}
Also, to show the nested data object we return, we can use Blaze dot syntax in the contextExample template by adding the following line of code to the template:
<p>{{someNested.text}}</p>

This will now display both the someText and the someNested.text, which was returned by our helper functions.

Using the {{#with}} block helper

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:

{{#with dataContextHelper}} {{> contextExample}} {{/with}}

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:

{{#with dataContextHelper}} <p>{{someText}}</p> <p>{{someNested.text}}</p> {{/with}}

Adding events

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:

<button>Get some random number</button>

To catch the click event, open examples.js and add the following event function:

Template.contextExample.events({ 'click button': function(e, template){ Session.set('randomNumber', Math.random(0,99)); } });

This will set a session variable called randomNumber to a random number.

Note

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:

Template.contextExample.helpers({ logContext: function(){ console.log('Context Log Helper',this); return Session.get('randomNumber'); } });

If we go to the browser, we will see the Get some random number