How to Set Up a Basic Ember.js App: A Beginner‘s Guide

Ember.js is a popular JavaScript framework for building ambitious web applications. Developed by Yehuda Katz and Tom Dale in 2011, it has evolved into a productive and opinionated tool for crafting maintainable client-side apps. In this tutorial, we‘ll walk through the process of setting up a basic Ember app from scratch.

Why Choose Ember.js?

Ember follows a "convention over configuration" philosophy, which means it provides a set of standard practices and tools out of the box. This reduces the mental overhead of making architectural decisions and lets developers focus more on building their app-specific logic. Ember also offers:

  • A friendly CLI for quickly scaffolding new projects and files
  • Handlebar templates for writing dynamic HTML
  • A powerful router for mapping URLs to templates and models
  • Data binding between JavaScript models and HTML views
  • Built-in testing tools for ensuring your app is bug-free

While Ember has a non-trivial learning curve compared to more lightweight options like Vue or vanilla JavaScript, many developers find that it scales well to large codebases and teams. Companies like LinkedIn, Twitch, and Apple use Ember to power complex web apps.

Setting Up Your Environment

Before we create our first Ember app, let‘s make sure your development environment is ready to go. You‘ll need:

  1. Node.js – Ember CLI is built on top of Node, so you need Node installed on your machine. Visit the official Node.js site and download the version labeled "LTS" for your operating system.

  2. npm – Once you install Node, you get npm (Node Package Manager) as well, which lets you install JavaScript packages and tools. The Ember CLI uses npm behind the scenes.

  3. Ember CLI – With Node and npm ready, you can install the Ember command line interface globally by running:

npm install -g ember-cli

This will make the ember command available in your terminal. You can verify it‘s installed by running:

ember --version

Generating a New App

Now the fun begins! Let‘s generate the boilerplate files for a new Ember app called "ember-quickstart". In your terminal, navigate to the folder where you want your app to live and run:

ember new ember-quickstart

You‘ll see Ember CLI‘s friendly messages as it generates the necessary files and installs npm and Bower dependencies. This might take a minute or two.

Ember CLI output

Once the process finishes, cd into your new app folder:

cd ember-quickstart

We can immediately serve our app locally by running:

ember serve

Visit http://localhost:4200 in your web browser and you‘ll see the default Ember welcome page:

Default Ember welcome page

Congratulations, you just created and served your first Ember app! Let‘s explore what‘s happening under the hood.

Touring the App Structure

Open your new ember-quickstart folder in your favorite code editor. You‘ll see a file tree that looks like this:

ember-quickstart
├── app
│   ├── app.js
│   ├── components
│   ├── controllers
│   ├── helpers
│   ├── index.html
│   ├── models
│   ├── router.js
│   ├── routes
│   ├── styles
│   └── templates
├── config
│   ├── environment.js
│   └── targets.js
├── public
└── tests
    ├── integration
    └── unit

Let‘s break down the key files and folders:

  • app: This folder contains the meat of your Ember app. All your models, routes, components, templates, and styles will live here. The app.js and router.js files set up your app and route declarations respectively.

  • config: This holds environment-specific configuration. You probably won‘t need to edit these files directly unless you‘re deploying to production.

  • public: Any static assets (images, videos, fonts, etc) that don‘t go through Ember‘s asset pipeline can be placed in the public folder. They‘ll be copied verbatim when you build your app for deployment.

  • tests: Ember CLI generates a test file whenever you use its generators to create a new component, route, service, etc. It encourages testing by default.

Working with Routes and Templates

Let‘s add a new route to our app. We want a dedicated page that shows an inspirational quote. To generate a route, stop your ember serve session with Ctrl + C and run:

ember generate route quote

Ember CLI will generate the appropriate route, template, and test files for us:

installing route
  create app/routes/quote.js
  create app/templates/quote.hbs
updating router
  add route quote
installing route-test
  create tests/unit/routes/quote-test.js

Open the newly created app/templates/quote.hbs file and add:

<h2>Random Quote</h2>

<p>"The only way to do great work is to love what you do." - Steve Jobs</p>

Next, let‘s link to our quote route from the homepage. Open app/templates/application.hbs and replace the contents with:



{{#link-to ‘quote‘}}
  View Random Quote
{{/link-to}}

{{outlet}}

Here we use the link-to helper to create a link to our quote route. The outlet helper tells Ember where to render the content of the current active route.

Start your server again with ember serve and click the "View Random Quote" link. You should see your quote page rendered.

Creating a Component

As your app grows in complexity, you‘ll want to break your UI into reusable and composable components. Let‘s refactor our random quote into a standalone component.

Generate a new component with:

ember generate component random-quote

Ember will generate the following files:

installing component
  create app/components/random-quote.js
  create app/templates/components/random-quote.hbs
installing component-test
  create tests/integration/components/random-quote-test.js

Open the app/templates/components/random-quote.hbs file and move your quote markup there:

<h2>Random Quote</h2>

<p>"The only way to do great work is to love what you do." - Steve Jobs</p>

Now in your app/templates/quote.hbs file, replace the markup with your newly created component:

{{random-quote}}

Reload your quote page and it should look exactly the same. We‘ve just made our quote more reusable by moving it into a component.

Fetching and Displaying Data

Static templates are boring. Let‘s fetch some data from an API to make our random quote more dynamic.

First, install the ember-ajax addon. This will give us an easy way to make HTTP requests to APIs. Stop your server and run:

ember install ember-ajax

Next, we‘ll create an Ember service to fetch quotes from the "Quotes on Design" API. Generate a new service with:

ember generate service quote-fetcher

Open the newly created app/services/quote-fetcher.js file and add the following code:

import Service from ‘@ember/service‘;
import { inject as service } from ‘@ember/service‘;

export default class QuoteFetcherService extends Service {
  @service ajax;

  async fetchRandomQuote() {
    const response = await this.ajax.request(‘https://quotesondesign.com/wp-json/wp/v2/posts/‘);

    const randomQuote = response[Math.floor(Math.random() * response.length)];

    return {
      text: randomQuote.content.rendered,
      author: randomQuote.title.rendered,
    };
  }
}

This service has a fetchRandomQuote method that makes a request to the API, plucks a random quote from the response, and returns an object with the quote text and author name.

Now let‘s use this service in our random-quote component. Open app/components/random-quote.js and update it like so:

import Component from ‘@glimmer/component‘;
import { tracked } from ‘@glimmer/tracking‘;
import { action } from ‘@ember/object‘;
import { inject as service } from ‘@ember/service‘;

export default class RandomQuoteComponent extends Component {
  @service quoteFetcher;
  @tracked quote = {};

  constructor() {
    super(...arguments);
    this.fetchNewQuote();
  }

  @action
  async fetchNewQuote() {
    this.quote = await this.quoteFetcher.fetchRandomQuote();
  }
}

Here‘s what‘s happening:

  1. We inject our quote-fetcher service using the @service decorator. This lets us access our service as this.quoteFetcher within our component.

  2. We create a @tracked quote property to hold the current quote object. The @tracked decorator tells Ember to rerender our component whenever this property changes.

  3. In the component‘s constructor, we immediately fetch a random quote using our service.

  4. We define a fetchNewQuote method decorated with @action. This will let us attach this method to a button in our template to fetch a new quote on demand.

Finally, update your app/templates/components/random-quote.hbs file to use the dynamic quote data:

<h2>Random Quote</h2>

<p>{{{this.quote.text}}}</p>
<cite>- {{this.quote.author}}</cite>

<button type="button" {{on "click" this.fetchNewQuote}}>
  Fetch New Quote
</button>

Note that we use the triple curly brace syntax {{{ to render the quote text as HTML, since it comes back from the API with some formatting tags.

We also attach our fetchNewQuote action to a button using the on modifier. This will call our action method whenever the button is clicked.

Reload your quote page and you should now see a random quote fetched from the API, with the ability to fetch a new quote on demand!

Building and Deploying

Once you‘ve finished developing your Ember app, you‘ll probably want to deploy it so users can access it on the public web.

To build your app for production, run:

ember build --prod

This will compile, minify, and fingerprint your assets into a dist folder. You can deploy the contents of this folder to any web server or static hosting service.

One popular (and free!) option is deploying to Netlify. They have a great guide on deploying Ember apps here: https://www.netlify.com/blog/2017/06/23/how-to-deploy-an-ember-app-to-netlify/

Next Steps

Congratulations! You now have a solid foundation for building Ember apps. We‘ve only scratched the surface of what Ember can do. As next steps, I‘d recommend:

  • Reading through the official Ember guides and API docs
  • Exploring popular addons like Ember Data for managing your models and data persistence
  • Learning testing best practices with Ember‘s built-in testing tools
  • Deploying a backend API (in Rails, Express, Laravel, etc) to persist your app‘s data
  • Joining the welcoming Ember community on Discord, forums, and meetups

I hope this guide has piqued your interest in Ember and shown you how productive it can be for building ambitious web applications. Happy coding!

Similar Posts