1

I'm working on Angular 2/4/5 application for a while now (that's why 2/4/5), using webpack to bundle everything, etc. The application itself communicates with a backend API written in C#. We're at a stage right now that we need to support 4 different environments which results in 4 different endpoints for the mentioned backend API, so I started exploring options how I can replace the values for the endpoints during npm run build:environment in combination with VSTS build definition that should also do the transformation when running a specific script.

This is how the config file looks like:

const AppConfig = {     
    hubName: "eventhub",
    baseApiUrl: "https://endpoint.com/api/",
    baseUrl: "https://endpoint.com/"
};

I started with webpack.prod.js and webpack.dev.js and I have two scripts configured: build:prod and build:dev. Both of those webpack files are setting the value for process.env.ENV to production and development respectively. Using that info, I tried reading the value for process.env.ENV in config.ts file and just doing switch/case and setting the value for baseApiUrl and baseUrl based on the value, however that didn't work, it kept defaulting back to development all the time, so I abandoned that approach and started exploring other options, like using normalModuleReplacementPlugin for webpack, but with little success.

Are there any better ways of replacing specific properties of a config file during execution of the build task?

Milan Stojanovic
  • 307
  • 1
  • 14
  • I think [this](https://stackoverflow.com/questions/38116352/best-practices-of-config-value-update-for-build-definitions?rq=1) SO post will help you with what you need and set you on the right track – ThePretendProgrammer Nov 10 '17 at 14:11
  • Thanks! This post provided valuable insights for me, however the proposed answer is actually a perfect solutions for me. – Milan Stojanovic Nov 11 '17 at 09:40
  • I am wondering, how is this not getting much more attention and how is this not solved yet by angular team? – eddyP23 Aug 16 '18 at 11:40

1 Answers1

1

You can do even better with webpack DefinePlugin since it would replace variables right inside your typescript code with the value you would specify in your webpack config files.

PS: but in my case I don't specify exact values - instead I read values from process.env inside webpack config so I do need only one config:

plugins: [
    new webpack.DefinePlugin({
        ENV: JSON.stringify(process.env.ENV)
    })
]
Pavel Agarkov
  • 3,633
  • 22
  • 18