What is the preferred way to install phase media in Polymer applications?

I am building a web application using Polymer from an application template through polymer init starter-kit.

I have an environment variable for a specific phase, such as an API entry point. There is a behavior for these environment variables:

<script>
  EnvBehavior = {
    properties: {
      apiBaseUrl: {
        type: String,
        // value: '//some-url.com'     // production
        value: 'http://localhost:8000' // development
      }
    }
  };
</script>

And apiBaseUrlused 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>

It works. But I would like to create a production application with apiBaseUrla default value //some-url.comthat is commented out in the code. How can I effectively set phase variables for build time? I use polymer-cli to build; follow up polymer build.

+4
source share
2 answers

JS EnvBehavior, . , :

  • env-behavior.js ( ),
  • env-behavior.js.stage ( )
  • env-behavior.js.production ( ).

, .

, polymer serve, ( , ). , env-behavior.js , , env-behavior.js.production .

post-build gulp polymer build, polymer-build code.

, , :

  • (, , ).
  • .
+5

, polymer-cli.

apiBaseUrl , .

:

properties: {
    apiBaseUrl: {
        type: String,
        value: function() {
            if (window.location.hostname === 'localhost') {
                return 'http://localhost:8000';
            } else {
                return '//some-url.com';
            }
        }
    }
}
+1

Source: https://habr.com/ru/post/1655031/


All Articles