I'm building an web app using Polymer from an app template via polymer init starter-kit
.
I have some phase-specific environment variable such as backend API entrypoint. There's a behavior for those environment variables:
<script>
EnvBehavior = {
properties: {
apiBaseUrl: {
type: String,
// value: '//some-url.com' // production
value: 'http://localhost:8000' // development
}
}
};
</script>
And apiBaseUrl
is used in other elements:
<dom-module id="my-element">
<template>
<iron-ajax url="{{apiBaseUrl}}/foo" method="POST"
content-type="application/x-www-form-urlencoded"
body="{{requestBody}}" handle-as="json"
on-response="onResponse" on-error="onError"></iron-ajax>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
requestBody: {foo: 'bar'}
},
behaviors: [EnvBehavior],
onResponse: function(e) {
console.log(e.detail.response);
},
onError: function(e) {
console.log(e.detail.request.xhr.response);
}
});
</script>
</dom-module>
This works. But I'd like to build an app for production with apiBaseUrl
's default value //some-url.com
, which is commented out on the code. How can I effectively set phase-specific variables on build time? I use polymer-cli for build; run polymer build
.
Since it looks like you are already using a separate JS file for implementing the EnvBehavior
, you could do the following. Create multiple versions of this file, for example:
env-behavior.js
(for local),env-behavior.js.stage
(for stage), andenv-behavior.js.production
(for production).Obviously, put appropriate configuration values within each file.
With this, when you will be using polymer serve
everything should work with the local version (since it is included by default when no file-swapping is done). But when you build for a specific environment, you simply overwrite the env-behavior.js
with, say, env-behavior.js.production
when deploying to production.
For swapping files, you can create a manual post-build gulp task or even customize the polymer build
command by altering the polymer-build code.
Also, I would strongly advise agains using client side checks for selecting the appropriate config values, because:
There is no feature that lets you do this with the polymer-cli
.
Instead of manually changing the apiBaseUrl
property for development and production you could detect which environment it's running in.
Example:
properties: {
apiBaseUrl: {
type: String,
value: function() {
if (window.location.hostname === 'localhost') {
return 'http://localhost:8000';
} else {
return '//some-url.com';
}
}
}
}
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