7

I have an Angular app with the following simple config file config.js:

export default function(app) {
  app.constant('config', {apiUrl: 'https://localhost:8080'});
};

which is imported by Webpack entry point app.js:

import config from './config';
config(app);

I'd like to have a different apiUrl when I do production build.

What's the easiest way to do it in Webpack?

3
  • 1
    I don't have the exact answer as I don't use webpack. I'm stuck using ASP.NET bundling at the moment, but the way we achieve the same thing (for our API endpoint) is to bundle a different file that defines the same constant (different values), depending on our target environment, e.g. production -> prod/config.js; uat -> uat/config.js. Commented Jan 10, 2016 at 20:41
  • Yes, this was one of the options, before I decided to have one file with switch on location.hostname Commented Jan 11, 2016 at 12:08
  • Check out my solution on Github, I can't believe how hard it seems to be to find a simple solution for passing Configurations from webpack cmd to Angular2 Typescript, my solution is very simple, github.com/Sweetog/yet-another-angular2-boilerplate Commented Feb 24, 2017 at 21:45

2 Answers 2

2

There is a similiar question on https://stackoverflow.com/a/34032050/1610981

It relates you can use http://webpack.github.io/docs/list-of-plugins.html#defineplugin

The config.js file would be this:

export default function(app) {
  app.constant('config', {apiUrl: API_URL});
};

And inside of webpack config files:

plugins:[
  new webpack.DefinePlugin({
    API_URL: JSON.stringify('https://localhost:8080')
  })
]

You should have two webpack configs, one for develoment and another for production. Each one defines API_URL macro, according with the built performed.

Sign up to request clarification or add additional context in comments.

1 Comment

I have several production builds for staging also. How do I solve it with the approach use suggested?
1

I recommend use environment variable with webpack.DefinePlugin

//webpack.config.js
...

let API_URL;
if (process.env.NODE_ENV == 'development') {
  API_URL = 'https://dev:8080';
} else {
  API_URL = 'https://prod:8080';
}

// or

const API_URL = process.env.API_URL;

...

plugins:[
  new webpack.DefinePlugin({API_URL: API_URL})
]
...

If NODE_ENV not setuped use export NODE_ENV=development for linux/osx or SET NODE_ENV=development for windows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.