How do I access ENV from config/environment in an addon?

367 Views Asked by At

This is a question that was asked by @dbendaou over on the Ember Discord


What is the best way to access ENV from config/envirnoment in an addon?

I was thinking about getOwner(this).lookup('config:environment') but it doesn't work neither does import ENV from '../config/environment';

1

There are 1 best solutions below

0
On

From addons, specifically, since your context doesn't define the environment, you need a slightly different API:

import { getOwner } from '@ember/application';

// ....
export default class MyAddonComponent extends Component {
  get env() {
    getOwner(this).resolveRegistration('config:environment')
  }
}

import ENV from '../config/environment' is an alias for import ENV from '<app-name>/config/environment'; which, addons can't know what the <app-name> is.

Maybe related, because this has come up a number of times in the discord, is that this would also be how you get access to environment variables at runtime. environment.js is a build-time file, so it has access to the node environment your app builds in and it outputs a JSON object for your app to consume.

For example:

// <your-app>/config/environment.js

const MY_ENV_VAR = process.env;

module.exports = function (environment) {
  let ENV = {
     // ...
     MY_ENV_VAR,

  };

  return ENV;
}

Then, your addon can access MY_ENV_VAR via resolveRegistration. and apps can access it via the import.

Apps:

import ENV from '<app-name>/config/environment'

// ...
ENV.MY_ENV_VAR

Addons:

getOwner(this).resolveRegistration('config:environment').MY_ENV_VAR;