Search code examples
ember.jsember-clinpm-scripts

EmberJs: how to dynamicaly inject data into ENV?


I need to dynamically inject some data before build stage.

In my config/environment.js i have:

module.exports = function(environment) {
  environment = 'production';
  var ENV = {
    APP: {
      API_HOST: 'https://apihost1.com,
      secret: 'key1'
     }
   };
  return ENV;
};

How do i can to dynamically change "APP" object to something else:

    APP: {
      API_HOST: 'https://apihost2.com,
      secret: 'key2'
     }

before build according to an executing command in my package.json?

"scripts": {
    "build": "$CONFIG_NAME ember build",
},

I was thinking about npm scripts but could not implement that. Is anyone has a solution for it?


Solution

  • You could do something like this in config/environment:

    const customConfig = require(`./config.${process.env.CONFIG_NAME}.json`);
    
    module.exports = function(environment) {
      environment = 'production';
      var ENV = {
        APP: {
          ...customConfig,
          otherStuff: 'bla'
         }
       };
      return ENV;
    };
    

    then you can run env CONFIG_NAME=foo ember build if you want to merge the content of the config/config.foo.json into the ENV.APP during the build.

    env tho is a unix thing, this will work on Linux and MacOS as well as other unix systems.

    For windows you can either set the env variable with PowerShell or install cross-env and do npm run cross-env CONFIG_NAME=foo ember build.