Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 556
krl Avatar asked Jan 09 '16 10:01

krl


2 Answers

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.

like image 82
dvdvck Avatar answered Nov 15 '22 03:11

dvdvck


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.

like image 28
Stan Kondrat Avatar answered Nov 15 '22 03:11

Stan Kondrat