0

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?

trigger
  • 489
  • 10
  • 26
  • Does [this](https://stackoverflow.com/questions/62423370/how-to-hide-a-section-in-hbs-and-js-while-taking-an-ember-production-build/62468171#62468171) answer your question? – Lux Jul 15 '20 at 13:55
  • Thanks, almost, but not 100% matches. I want to change an object in env without "if (cross-env value) " conditions. – trigger Jul 15 '20 at 14:55
  • I'm not sure I understand. You need that if to differentiate different configs. – Lux Jul 15 '20 at 14:58
  • yes, and i just need to pass a config by name because i have a 30 configs. I do not want to have 30 build scripts lines in package.json and 30 if conditions in environment.js file – trigger Jul 15 '20 at 15:19
  • Ah. I see. You could do something like `require(process.env.CONFIG_NAME)`. Then you can do `env CONFIG_NAME=foo ember build `! – Lux Jul 15 '20 at 15:22
  • sorry, I do not get it. I have 30 config files: config.PLATFORM.json with { API_HOST: 'https://apihost1.com, secret: 'key1'} ....etc. How to apply your answer this this? – trigger Jul 15 '20 at 15:45
  • How do you want to decide which config to use? – Lux Jul 15 '20 at 16:09
  • If you have 30 config files that only affect the run-time configuration of your Ember application but does not affect any other part of your build, you may want to consider manually replacing run-time configuration in `index.html` after the build. This should be way more performant for such a number of scenarios as it would only require one build, copying a file 30 times and and doing some search and replace in it. – jelhan Jul 15 '20 at 17:51

1 Answers1

2

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.

Lux
  • 17,835
  • 5
  • 43
  • 73