basset
basset copied to clipboard
conditionally load javascript based on environment from within closure
While developing on local I want to use the public google maps api so I don't use up my requests, however when on production I need the url which contains a key to authenticate.
How can I conditionally load one or the other based on the environment. I tried to debug and saw there was an $env variable however it's always 'environment' which I assume is based on my laravel rules. However when I compile for production with
php artisan basset:build --production
I would expect that variable to be 'production' but it's not. I've also noticed there is $argv attributes that I can read, my hack below uses that where I consider it production build if there are 3 arguments 'php artisan' 'basset:build' '--production'
Is this the right way of doing this? I noticed there was whenProductionBuild() but that's only for a filter correct?
'home' => function($collection)
{
$directory = $collection->directory('assets', function($collection) {
$collection->stylesheet('css/bootstrap/bootstrap.min.css');
$collection->stylesheet('css/bootstrap/bootstrap-responsive.min.css');
if ($GLOBALS['env'] == 'production' || isset($GLOBALS['argv']) && (count($GLOBALS['argv']) == 3 && $GLOBALS['argv'][2] == '--production')) $collection->javascript('https://maps.google.com/maps/api/js?key=mykeyhere&sensor=false');
else $collection->javascript('http://maps.google.com/maps/api/js?sensor=false');
});
$directory->apply('CssMin')->whenProductionBuild();
$directory->apply('UriRewriteFilter');
$directory->apply('JsMin')->whenProductionBuild();
},
``
No you should probably use Laravel's environment. Then can be configured in bootstrap/start.php
either with machine names or URLs.
And then in your collection you use if (App::environment() == 'production')
.
The problem when I run the compile for production command line from my local environment it will think its local , our workflow is we compile locally then push rsync to the server.
I think running php artisan basset:build --production
doesn't really sets the App environment to production. Is just an internal flag for Basset.
Luckily, @jasonlewis provided a bunch of useful filters. You could do something like:
$collection
->javascript('https://maps.google.com/maps/api/js?key=mykeyhere&sensor=false')
->whenProductionBuild();
$collection
->javascript('http://maps.google.com/maps/api/js?sensor=false')
->whenDevelopmentBuild();
I haven't tested that code.
Read more: http://jasonlewis.me/code/basset/4.0/filters#production-build