Ember.js — Set up constants

What if you needed one place where you can access all of your constants in Ember? We want to write clear and concise code, and if we have a large project where each file contains 1000+ lines of code, we would want to separate the constants in another file right? It is good practice to modularize code anyway.

One thing you can do is declare constants as global variables. That’s not bad but it’s not considered the best practice because we might not use them in all our components, routes, or controllers, and having them live throughout the entire program could take up precious memory. We would want to look for a solution where it is efficient and convenient to inject these constants in places where we need to access them.

That’s where service injections using initializers comes in. More info on injecting services using initializers can be found here on the ember guide.

The gist of it is, you can create a service and an initializer using the Ember CLI command in the terminal at the root of your Ember application:

ember g service constants

ember g initializer constants

You can replace constants with your service and initializer name. Then in your service, you can create your constants:

I really like this way of injecting services into all routes (you can inject them into components and controllers too) because it’s more convenient and you don’t have to individually inject these services in each places where you need them. They’ll be injected from the initializer and that’s a plus for modularity and concise code.