Angular app API url configuration using webpack for dev and production builds

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

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

which is imported by the app.js entry point:

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

I want me to have another apiUrl when I do the assembly.

What is the easiest way to do this in webpack?

+6
source share
2 answers

I recommend using the webpack.DefinePlugin environment variable

 //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 is not set, use export NODE_ENV=development for linux / osx or SET NODE_ENV=development for windows.

+1
source

There is a similar question about fooobar.com/questions/999866 / ...

This applies to http://webpack.imtqy.com/docs/list-of-plugins.html#defineplugin

The config.js file will be as follows:

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

And inside the webpack configuration files:

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

You must have two webpack configurators, one for development and one for production. Each of them defines an API_URL macro, in accordance with the execution performed.

0
source

All Articles