krl
krl

Reputation: 5296

Angular application API URL configuration with Webpack for dev and production builds

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?

Upvotes: 7

Views: 5362

Answers (2)

Stan Kondrat
Stan Kondrat

Reputation: 147

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.

Upvotes: 1

dvdvck
dvdvck

Reputation: 435

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.

Upvotes: 2

Related Questions