Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Building Single-page Web Apps with Meteor
Building Single-page Web Apps with Meteor

Building Single-page Web Apps with Meteor: Build real-time single page apps at lightning speed using the most powerful full-stack JavaScript framework around

By Fabian Vogelsteller
$16.99 $10.99
Book Jan 2015 198 pages 1st Edition
eBook
$16.99 $10.99
Print
$26.99
Subscription
$15.99 Monthly
eBook
$16.99 $10.99
Print
$26.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 27, 2015
Length 198 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783988129
Vendor :
Meteor Development Group
Category :
Table of content icon View table of contents Preview book icon Preview Book

Building Single-page Web Apps with Meteor

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 Meteor

  • Meteor's requirements

  • Installing Meteor

  • Adding basic packages

  • Meteor's folder conventions and loading order

  • Meteor'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 changes

  • We can push new code to all clients on the fly while they are using our app

  • Meteor core packages come with a complete account solution, allowing a seamless integration of Facebook, Twitter, and more

  • Data will automatically be synced across clients, keeping every client in the same state in almost real time

  • Latency 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:

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:moment-with-langs@1.0.0

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.

Variable scopes


To understand Meteor's build process and its folder conventions, we need to take a quick look at variable scopes.

Meteor wraps every code files in an anonymous function before serving it. Therefore, declaring a variable with the var keyword will make it only available in that file's scope, which means these variables can't be accessed in any other file of your app. However, when we declare a variable without this keyword, we make it a globally available variable, which means it can be accessed from any file in our app. To understand this, we can take a look at the following example:

// The following files content
var myLocalVariable = 'test';
myGlobalVariable = 'test';

After Meteor's build process, the preceding lines of code will be as follows:

(function(){
  var myLocalVariable = 'test';
  myGlobalVariable = 'test';
})();

This way, the variable created with var is a local variable of the anonymous function, while the other one can be accessed globally, as it could be created somewhere else before.

Meteor's folder conventions and loading order


Though Meteor doesn't impose restrictions concerning our folder names or structure, there are naming conventions that help Meteor's build process to determine the order in which the files need to be loaded.

The following table describes the folder and their specific loading order:

Folder name

Load behavior

client

This is loaded only on the client.

client/compatibility

This will not be wrapped in an anonymous function. This is made for libraries that declare top-level variables with var. Additionally, files in this folder will be loaded before other files on the client.

server

Files in this folder will only be served on the server.

public

This folder can contain assets used on the client, such as images, favicon.ico, or robots.txt. Folders and files inside the public folder are available on the client from root, /.

private

This folder can contain assets that will only be available on the server. These files are available through Assets API.

lib

Files and subfolders inside a lib folder will be loaded before other files, where lib folders in deeper folders will be loaded before the files in lib folders of their parent folders.

tests

Files inside this folder won't be touched or loaded by Meteor at all.

packages

When we want to use local packages, we can add them to this folder and Meteor will use those packages, even if one with the same name exists in Meteor's official package system. (However, we still have to add the packages using $ meteor add ....)

The following table describes filenames that have created a specific loading order:

Filename

Load behavior

main.*

Files with this name are loaded last, whereas files in deeper folders are loaded before the files of their parent folders

*.*

Files outside of the former mentioned folders in this table are loaded on both the client and server

So, we see that Meteor gathers all files except the ones inside public, private, and tests.

Additionally, files are always loaded in the alphabetical order, and files in subfolders are loaded before the ones in parent folders.

If we have files outside the client or server folder and want to determine where the code should be executed, we can use the following variables:

if(Meteor.isClient) {
  // Some code executed on the client
}

if(Meteor.isServer) {
  // Some code executed on the server. 
}

We also see that code inside a main.* file is loaded last. To make sure a specific code only loads when all files are loaded and the DOM on the client is ready, we can use the Meteor's startup() function:

Meteor.startup(function(){
  /*
  This code runs on the client when the DOM is ready,
  and on the server when the server process is finished starting.
  */
});

Loading assets on the server

To load files from inside the private folder on the server, we can use the Assets API as follows:

Assets.getText(assetPath, [asyncCallback]);
// or
Assets.getBinary(assetPath, [asyncCallback])

Here, assetPath is a file path relative to the private folder, for example, 'subfolder/data.txt'.

If we provide a callback function as the second parameter, the Assets() method will run asynchronously. So, we have two ways of retrieving the content of an assets file:

// Synchronously
var myData = Assets.getText('data.txt');

// Or asynchronously
Assets.getText('data.txt', function(error, result){
  // Do somthing with the result.
  // If the error parameter is not NULL, something went wrong
});

Note

If the first example returns an error, our current server code will fail. In the second example, our code will still work, as the error is contained in the error parameter.

Now that we understand Meteor's basic folder structure, let's take a brief look at the Meteor's command-line tool.

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:

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.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Create reactive templates that update themselves when data changes Use database queries on the client and the server to retrieve, sort, and manipulate datasets Understand data synchronization using a publication/subscription model and make API calls a thing of the past Discover how you can secure your data flow on the server side to keep confidential data secret Add routing to a singlepage application and make it appear like a real website Build your own advanced reactive objects and make everything rerun when you want Make your own Meteor packages and learn how to make them public Unit test your packages and Meteor applications

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 27, 2015
Length 198 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783988129
Vendor :
Meteor Development Group
Category :

Table of Contents

21 Chapters
Building Single-page Web Apps with Meteor Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
Acknowledgments Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started with Meteor Chevron down icon Chevron up icon
Building HTML Templates Chevron down icon Chevron up icon
Storing Data and Handling Collections Chevron down icon Chevron up icon
Controlling the Data Flow Chevron down icon Chevron up icon
Making Our App Versatile with Routing Chevron down icon Chevron up icon
Keeping States with Sessions Chevron down icon Chevron up icon
Users and Permissions Chevron down icon Chevron up icon
Security with the Allow and Deny Rules Chevron down icon Chevron up icon
Advanced Reactivity Chevron down icon Chevron up icon
Deploying Our App Chevron down icon Chevron up icon
Building Our Own Package Chevron down icon Chevron up icon
Testing in Meteor Chevron down icon Chevron up icon
Appendix Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.