Ember CLI is a Node.js-based command-line interface tool designed for application programming in Ember.js. Since its creation, this tool has become the preferred method to create Ember applications.
Simply put, Ember CLI makes starting a new Ember application easy. In other frameworks, you might need to learn gulp or grunt as your task runners. In Ember CLI, this is all built-in for you. Having Ember CLI in the Ember.js ecosystem is a game changer and makes this framework stand out above the rest.
Ember CLI handles testing, compiling, and upgrading, and even has a built-in web server. Ember CLI not only generates boilerplate code for you, but it also integrates nicely with many testing frameworks. It has a robust add-on system that extends the functionality well beyond its current capabilities.
The installation of Ember CLI is essential to learning Ember and will be used throughout this book.
Before the installation of Ember CLI, we must have the Node Package Manager (npm) installed. npm
is a package manager for JavaScript and is installed by default with Node.js.
You must install version 0.12 or later of Node.js for Ember CLI to run. If you can, try to install version 4.0.0 or higher. This is the preferred version.
Node.js is available in several major platforms including Windows, Mac, and Linux. There are several ways to install Node.js:
One-click installers: Many platforms such as Windows and Mac have this available
Homebrew or MacPorts: This is useful for Mac OS users
Download TAR file: Download a TAR file of Node.js and extract
Install via the Linux package management system: Yum, apt-get, or pacman can be used to install on a Linux environment
This method is by far the easiest. To install node, you'll need to open the node website at http://nodejs.org/download. Click on the pkg
, msi
, or exe
installer for Windows or Mac. Run it after it's downloaded.
If you already have Homebrew installed, just run the following command:
$ brew install node
On the other hand, if you are running MacPorts, you can use the port install command:
$ sudo port install nodejs
Tip
MacPorts can be installed from http://www.macports.org. Homewbrew can be installed from http://brew.sh. Both offer simple package management for OS X systems.
A TAR file is a type of archive file. To install node via a TAR, you will need to download the TAR file from the Node.js website and extract and install it. One way of doing this is to use curl
.
I would only recommend this method if you are using a Linux distribution. If you are running on Linux, you'll need the right tools installed to compile from source. On Ubuntu, you'll need to install the build-essential and curl
packages:
$ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1 $ ./configure $ sudo make install
All major Linux distributions offer Node.js packages. In Ubuntu, you can simply use apt-get
:
$ sudo apt-get install nodejs
In Fedora, you can use yum
:
$ yum install nodejs npm
Check with your Linux distribution to find out more details on how to install packages such as Node.js. Be aware that some distributions might offer outdated versions of Node.js. In this case, I would recommend that you use the Node Version Manager (NVM) installation method that will be discussed later.
To test your installation, run the –v
command:
$ node –v $ npm –v
This will show the current installed version. Keep in mind that you must run v0.12 or above to run Ember CLI. If possible, try to run v4.0.0 or above.
Tip
The NVM is a bash script that helps manage multiple active Node.js versions. NVM offers a very simple command-line interface to install any version of Node.js without having to visit the Node.js website. It separates each installation making it very easy to change between versions. I would recommend most beginners on Mac and Linux to run this. You can download NVM at https://github.com/creationix/nvm.
We'll need to use npm
to install Ember CLI. We'll install it globally with the –g
option so that it can be run anywhere from the command line.
Open the command prompt and type the following command:
$ sudo npm install –g ember-cli
If NVM was installed, you don't need
sudo
at the start of the command.After Ember CLI is installed, we'll need to download Bower. Bower is a package manager for client-side programming and another essential component of Ember.js. Node.js and npm must be installed before beginning the installation of Bower. We'll be using Bower to install all our client-side libraries:
$ sudo npm install –g bower
Similar to the last command, you don't need
sudo
at the start of the command if Node.js was installed via NVM.The last step is to install PhantomJS. PhantomJS is a scripted headless browser used to automate and test web pages. It's preferred by Ember CLI and needs to be installed:
$ npm install –g phantomjs
If you are on Windows, install the Ember CLI Windows tool:
$ npm install ember-cli-windows –g
Once installed, this tool can be run in any project directory:
$ ember-cli-windows
Make sure to download and install Git for Windows: https://git-scm.com/downloads
Note
Working with Windows
Build times on Windows can be longer then Mac or Linux. The Ember CLI Windows tool can help speed up and optimize build performance. Just run it in the project directory. You can also download it as an add-on instead.
Another way to help with performance is to always run PowerShell/CMD with elevated privileges. Otherwise, performance issues and errors might occur. Lastly, try to use npm version 3 or higher. You may run into issues with long file paths with older versions in Windows.
Another handy tip is as follows:
Tip
Optional: Install Watchman
Watchman is a file-watching service for OS X and UNIX-like operating systems. It was developed by Facebook and is a more effective way for Ember CLI to watch project changes. If it's not installed, Ember CLI will fall back to using NodeWatcher. NodeWatcher is more error-prone and has trouble observing large trees. Install Watchman if your platform supports it. To download and configure Watchman, visit https://facebook.github.io/watchman/.
Ember CLI is written in Node.js and can be installed via npm. The tool interprets commands from the user to help create an Ember.js application. Each command from the user is looked up and then executed. Ember CLI relies on several other dependencies including Bower, Lodash, Broccoli, and Babel, to name a few.
Let's take a look at commands and aliases.
Once Ember CLI is installed, we'll have access to several commands. Here is a short list of some of the more important ones:
Command |
Purpose |
---|---|
|
This prints a list of available commands |
|
This creates a directory called |
|
This creates an application in the current directory |
|
This builds the application in the |
|
This starts a web server |
|
This runs a generator that builds scaffolding for the project |
|
This uninstalls the module that was created by the generator |
| |
|
This installs add-ons |
Keep in mind that for every command, there is an alias. These aliases make it a little quicker to run commands. Suppose that you wanted to build a new project. Normally, you would type this:
$ ember build
This will work and is fine. It will generate a new project and application structure. You can also use an alias.
$ ember b
Here is a list of some common aliases that you can use. This is optional.
Command |
Alias |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
In this recipe we'll create our first project.
We'll begin with the Ember CLI tool to create our first project.
Open the command prompt and type the following command:
$ ember new my-project
This will create a brand new project called
my-project
. The project structure will have everything that we need to get started.To display this project, we can simply run the server command:
$ cd my-project $ ember server
The
ember server
command will start up a web server on port 4200. You can access this port by openinghttp://localhost:4200
. You should see the default Welcome to Ember website.Tip
It is a good idea to keep the Ember server running while developing your application. Ember CLI uses a tool called LiveReload to refresh the web browser when changes are made. This can be useful to see how new changes are affecting your application. To run LiveReload, simply type
ember server
. This will start the server with LiveReload.The server command defaults to port 4200. You can easily change this using the
--port
argument:$ ember server --port 1234
This will start the server on port
1234
instead of the default 4200.Another useful option is the
--proxy
argument. This will proxy all Asynchronous JavaScript and XML (Ajax) requests to the given address. Let's say that we have a node server running on port8080
. We can run the server as follows:$ ember server --proxy http://127.0.0.1:8080
For every Ajax request, Ember now will send these requests to the localhost at port
8080
.
The ember server
command creates a Node.js Express server. This server uses LiveReload and refreshes the web page whenever any changes are made. The server command accepts different arguments, including --proxy
and --port
.
When running the server, you have access to tests. After you start the server, you'll have access to the
QUnit interface. QUnit is a JavaScript unit testing framework. It is used to run your integration and acceptance tests. To access the interface, navigate your browser to http://localhost:4200/tests
. This will show all your tests in the project. From here, you can see which tests passed and which failed. We will cover this in the later chapters:
Ember CLI will create our folder structure for us. Ember.js uses the model-view-controller (MVC) pattern. You'll see in this recipe how the folder structure is laid out and how the model, controller, and view (templates) are separated from each other.
Ember CLI relies on ES2015 modules. This means that you can write code today using tomorrow's JavaScript syntax. This is accomplished via the Ember Resolver.
Tip
ES2015
ECMAScript 6, also known as ES2015, is the upcoming version of the ECMAScript programming language. ES2015 includes several new features, including template strings, destructuring, arrow functions, modules, and class definitions, to name a few. This is all available now within your Ember project.
An ember pod is a different type of structure that organizes your modules by feature instead of type. As your project grows, you may want to organize your project by feature to help keep things organized. The Ember Resolver will look for a pod structure first before it looks at the traditional structure.
To set up the pod structure automatically, you can edit the .ember-cli
file in the root of your project directory and add this line:
{ "usePods": true }
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
This will set the default structure to always use pods. When using pods, it is a good idea to set the location where all pods live. To do this, you will need to edit the config/environment.js
file:
... var ENV = { modulePrefix: 'pod-example', .. podModulePrefix: 'pod-example/pods'
The podModulePrefix
property sets the POD path with the following format, {appname}/{poddir}
. In the preceding example, the pod directory is now set to /pods
in the app
folder. If the location is not set, all new modules will be created in the app/
folder.
After a new project is created, a normal folder layout is generated. This layout consists of several different types of modules. Here is a short description of each directory:
Directory |
What it does |
---|---|
|
Adapters help extend logic to communicate with a backend data store |
|
Components are used to help reuse code and must have a dash in their name |
|
Helpers are used for HTML reuse |
|
Initializers are run first and help set up your application |
|
This is a special type of Ember.Object used with multiple inheritance |
|
Routes help move through different application states |
|
This serializes your data model |
|
Transform is used to deserialize and serialize model attributes |
|
Utils are small utility classes |
|
Models hold the data store |
|
Templates use HTMLBars to display HTML to the user |
|
These are templates used in your components |
A new project app
folder with a default layout will look similar to this:
Each module will have its own directory. For example, the templates
folder will store all the templates while the components
controller will store all the components.
Let's say that we added a new post resource using pods. The following command will generate a new post model, route, and template, and it will update the router:
$ ember g resource posts
Now the filesystem will look like this:
Pods sorts directories by features. The post and posts folders are features and the files are named after the function they serve.
The directory structure in each Ember CLI project is by design. When creating a new project or generating new scaffolding, the CLI will place files in a certain directory with a certain naming structure that the Ember Resolver understands using the ES2015 format.
The Ember Resolver is responsible for the looking up of code in your application and converting the name conventions in the actual class files. With Ember pods, the resolver knows to look there first before the default structure.
In this recipe we'll take a look at how assets are added to a project.
In your application, at some point, you may want to add assets and minimize or fingerprint your project. This is done in the root
folder of your project in the ember-cli-build.js
file or in the asset
folder.
All the assets should be placed in the public/assets
folder. The assets can be referred throughout the program at assets/images/{image file}
. CSS files should be placed in the app/styles
folder.
By default, CSS and JavaScript files are minified during the production build process. There are ways to turn this functionality on and off. For example, let's say that you want to turn off the minification for both CSS and JavaScript. To do this, we can simply edit the ember-cli-build.js
file, and under the // Add options here
section, add the minifyCSS
and minifyJS
section:
module.exports = function(defaults) { var app = new EmberApp(defaults, { // Add options here minifyCSS: { enabled: false }, minifyJS: { enabled: false } });
This will tell the compiler not to minify JavaScript and CSS. To build the application in the production mode, simply use the --environment
argument:
$ ember build --enviroment=production
All files by default will be fingerprinted during the production build process. This will include all js
, css
, png
, jpg
, and gif
assets. During this process, all these files will have an md5 checksum appended at the end of their filenames. During this process, all HTML and css files will be rewritten to include these new names.
There are several options available when fingerprinting a file. This is all controlled in the ember-cli-build.js
file. Let's suppose that you wanted to disable fingerprinting:
… fingerprint: { enabled: false } …
Another useful option is to prepend a domain to all static files. This can be done using the prepend
option. Once again, this needs to be added to the ember-cli-build.js
file in the root of the application
folder:
… fingerprint: { prepend: 'http://www.example.com' }
Now, all assets will include the www.example.com
domain. For example, a normal JavaScript src
file will look like this:
<script src="assets/script.js">
This will be transformed into the following:
<script src="http://www.example.com/script-12324adfasdf123234.js">
Another useful option is exclude
. This accepts an array of strings. Any filename in the exclude
array will not be fingerprinted:
fingerprint: { exclude: ['fonts/12424'] }
The ignore
option also accepts an array of strings. Any filename that contains any item in the ignore
array will not be processed or fingerprinted:
fingerprint: { ignore: ['fonts/12424'] }
The extension
option defaults to 'js'
, 'css'
, 'png'
, 'jpg'
, 'gif'
, and 'map'
. This option can be used to add other file types to get fingerprinted:
fingerprint: { extension: ['r3','html'] }
The replaceExtensions
option defaults to 'html'
, 'css'
, and 'js'
. If needed, new file types can be added to replace source code with new checksum file names:
fingerprint: { replaceExtensions: ['html','htm'] }
The import process is done via the Broccoli asset pipeline library. This build tool performs all the fingerprinting, minifying, and importing of the assets. In addition, Broccoli handles all the preprocessors if the appropriate plugins are installed.
The asset manifest is located in the ember-cli-build.js
file in the root of the project folder. You can only import assets that are in the bower_components
or vendor
directories.
Let's look at dependency management and how we can use it in our Ember projects.
Bower is used for dependency management for Ember CLI. Bower is a frontend tool that is used to help fetch and install packages that you might need.
The
bower.json
file is located in theroot
folder of your project. It contains all the dependencies. Let's say that we want to install the Bootstrap library:$ bower install bootstrap --save
This command will install
bootstrap
in thebower_components
folder and save the package information in thebower.json
file.Tip
Ember add-ons
Another popular way of adding third-party libraries to Ember is using add-ons or addons as you sometimes see it. An add-on is Ember's way of sharing libraries between applications. There are well over a thousand of them available.
You can install add-ons using Ember CLI. For example, to install Bootstrap, you'd type this on the command line in the project directory:
$ ember install ember-bootstrap
You can easily find a list of add-ons at these websites:
This will be discussed in more detail in the Working and creating add-ons recipe in Chapter 11, Real-Time Web Applications.
If, for some reason, you need to reinstall your dependencies, you can run the
install
command by itself:$ bower install
This will install all dependencies that are listed in the
bower.json
file.
Ember CLI allows you to load Asynchronous Module Definition (AMD) and non-AMD assets. It's a way of defining code modules and their dependencies.
To load a non-AMD asset, you'll need to import it using the
ember-cli-build.js
file:… app.import('bower_components/moment/moment.js');
This is useful as you can use Bower to install components, and then use the
app.import
AMD so that it's available in the program. You'll need to consult the package specification to see how to use it.Tip
Tip on JSHint
JSHint is a community-driven tool that detects errors and potential problems with JavaScript code. It's built-in in Ember CLI. When using non-AMD assets, you may get errors with JSHint if you have global variables. To fix this, add
/* global MY_GLOBAL */
at the top of your module page. In the moment example, it would look like/* global moment */
.AMD assets are imported in a similar way. You add the path in the first argument and a list of exports and modules in the second:
app.import('bower_components/ic-ajax/dist/named-amd/main.js', { exports: { 'ic-ajax': [ 'default', 'defineFixture', 'lookupFixture', 'raw', 'request', ] } });
To use this asset in your application, you can import it as follows:
import { raw as icAjaxRaw } from 'ic-ajax';;
Ember CLI is constantly being upgraded and every six weeks Ember.js has another release. It is important to keep your build tools and versions up to date. In this recipe we'll look at the best way of doing this.
To upgrade your Ember CLI version, you must perform the following steps:
Begin by uninstalling the old
ember-cli
:$ npm uninstall –g ember-cli
Clear the npm cache:
$ npm cache clean
Clear the Bower cache:
$ bower cache clean
Install the latest version of
ember-cli
:$ npm install –g ember-cli
If you need, you can specify the version to use represented by
X.X.X
:$ npm install –g ember-cli@X.X.X
In some situations, you might want to take an existing project and update it to the latest version of Ember CLI. In this case, you'll need to perform the following steps:
Begin by changing directories that you want to upgrade in the root of the project folder. Delete these temporary development directories:
$ rm –rf node_modules bower_components dist tmp
Update the
package.json
file with the version of Ember that we're upgrading to using this command:$ npm install ember-cli@X.X.X --save-dev
X.X.X
represents the version ofember-cli
. The--save-dev
argument will save the information in thepackage.json
file.Install all the npm and Bower packages again:
$ npm install $ bower install
The last step is to run the
init
command:$ ember init
The
init
command will add the default project blueprint to your directory.Tip
init
The
init
command will create a new application blueprint in your project directory. Follow the prompts and review all the changes. You may be asked to replace existing files. Press d to do a diff of the files and review the changes made. Create a backup of your project before you begin the upgrade process.
Keep in mind that after upgrading your project, you might have many new deprecation warnings to deal with. You will see these warnings when you run ember server
. Each one will need to be addressed.
To address these deprecations, view the warnings that the applications provide. For instance, you may get a warning about Ember.View
. The warning will describe that Ember.Component
should be used instead. You'll then need to swap out the effected code with Ember components instead of Ember views.
When you upgrade the tool, you are simply uninstalling the node package and reinstalling the latest one. It's a good idea to clear the Bower and Node cache as well so that Node and Bower won't have any conflicting packages.
When we update an existing project we first have to make sure that all the existing modules and packages are deleted. This is important because when we install the latest version of Ember CLI, some packages might change. After ember-cli
is saved back in the package file, then you can install npm
and Bower again.
Running ember init
generates the application structure in the directory that you're in. This is important because some files may have changed since the last upgrade. You can always press d to diff the changes.
After creating your application you'll need to be able to deploy it. Let's take a look at a few ways to deploy your application.
The first fundamental step before deployment is building your project. To build your application, run the
build
command:$ ember build
This command builds the contents of the project in the
/dist
folder. To build your project for production, you'll need to use the-prod
argument:$ ember build -prod
If you need, you can designate the default output folder:
$ ember build –prod –o<directory>
Building your application for production will automatically minify your files as well as fingerprint them. This does not occur when your environment is set up for development, which is set by default.
The /dist
folder has everything that your web server needs. At this point, to deploy your application, all you need to do is copy the contents of the /dist
folder to your web server.
Tip
Ember CLI Deploy
Another great way to deploy your Ember application is to use the Ember add-on called Ember CLI Deploy. This add-on helps you deploy your Ember application to a number of different services. It has a very active community behind it so you can expect frequent updates. As your Ember applications grows you may want to take a look at this. You can find more information about Ember CLI deploy here: https://github.com/ember-cli/ember-cli-deploy.
Firebase is a backend service that can handle data storage, user authentication, static hosting, and more. For this example we'll be using Firebase as a way to host our Ember application.
Sign up for an account with Firebase. This can be done at http://www.firebase.com.
Next, install the
firebase-tools
:$ npm install –g firebase-tools
After you have a project created and you're ready to deploy, run the
firebase init
command in the root of the folder:$ firebase init
After running this command, you'll be asked a few questions. It will first ask you to sign in to your Firebase account. Enter your credentials to continue. Then, it will ask for the name of your Firebase application. Lastly, it will ask for the name of your app's public directory. In most cases, this should be
/dist
.Edit the
firebase.json
file and add some rewrite rules:{ "firebase": "my-new-app", "public": "dist", "rewrites": [{ "source": "**", "destination": "/index.html" }], }
This is needed to help with navigation in the application. Change
my-new-app
to the name of your app as well.All that's left is to deploy to Firebase:
$ firebase deploy
The Ember CLI build process is compiled using the Broccoli asset pipeline and the build tool itself. It takes all the files and minifies, fingerprints, and organizes them in the /dist
folder so that it is ready to be deployed.
Many services exist that can host static files. You can use Firebase or just host it in your own Nginx or Apache server after building it for production.