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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With