Brunch how do you share/mixin code that changes based on where the finished app is running (app is a widget for 3rd party sites)?

StackOverflow https://stackoverflow.com//questions/11681151

  •  12-12-2019
  •  | 
  •  

Question

I'm trying to build a widget that will be hosted on 3rd party sites. Some of the external files it will depend on need to be pulled from different sources in different environments, i.e. in development, it should pull some files from localhost, in staging it should pull them from staging-domain.com, and in production, it should pull them from www.xyz.com

My hack solution is as follows -

in application.coffee:

prodApiHost = 'http://productionhost.com/api'

@APIHost = do ->
  if ( window.location.port.match(/^3/) || window.location.host.match(/^(localhost)/i) || window.location.host.match(/xyz.staging/i ))
    if window.location.host.match(/^(localhost)/i) || window.location.port.match(/^3/)
      window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/api'
    else
      window.location.protocol + '//' + window.location.host + '/api'
  else
    prodApiHost

Then, in the models where I need to use that URL, I do so as follows

in my_model.coffee:

some_attribute: namespacedApp.APIHost

I'm sure there's a better way... any pointers/help greatly appreciated!

EDIT

I found another way of doing this. I can put the same APIHost function in the initialize.coffee file like so:

application = require 'application'
application.prodApiHost = 'http://productionhost.com/api'

$ ->
  application.APIHost = do ->
    if ( window.location.port.match(/^3/) || window.location.host.match(/^(localhost)/i) || window.location.host.match(/xyz.staging/i ))
      if window.location.host.match(/^(localhost)/i) || window.location.port.match(/^3/)
        window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/api'
      else
        window.location.protocol + '//' + window.location.host + '/api'
    else
      application.prodApiHost

application.initialize()
Backbone.history.start()

Now the fn is available everywhere in the app. Still not sure this is the best solution. Any other suggestions?

Was it helpful?

Solution

I'd create small brunch plugin that will check if minifying is enabled (to determine production env) (config.minify) and make it add

if (window.brunch == null) window.brunch = {};
window.brunch.environment = ... (development / production)

and then check in your app

if (window.brunch.environment === 'production') {...} else {...}

I think separating dev / prod environments is a very common thing and in a bit brunch will receive “environments” abstraction for this purpose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top