Skip to content

Commit

Permalink
Run only in dedicated environments
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian Schöps committed May 4, 2021
1 parent 3cc97d5 commit cbc9d3f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Publish config (optionally):

Scripts in the `js-snippet` component will get minified (thanks to https://github.com/tedious/JShrink) and loaded as separate Javascript source.

You need to define the stack that the script tag will be pushed to (default: `scripts`).

By default this will only be run in the `production` environment (you can change this in the config).

## Behind the scenes
The component will minify its content and put it in a file in the view cache.
It will also generate a key based on the content.
Expand Down
6 changes: 6 additions & 0 deletions config/js-snippets.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
<?php

return [
// Stack that the script tag will be pushed to
'stack' => 'scripts',

// URL that will be used for the download of the compiled Javascript file
'url' => 'snippets',

// Environments in which this will be run
'environments' => ['production'],
];
6 changes: 5 additions & 1 deletion src/View/Components/Snippet.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ class Snippet extends Component
public function render()
{
return function (array $data) {
if(!in_array(app()->environment(), config('js-snippets.environments'))) {
return '@push("' . config('js-snippets.stack') . '")' . $data['slot'] . PHP_EOL . '@endpush';
}

$hash = md5($data['slot']);
$filepath = \Nanuc\JSSnippets\Snippet::getViewPathForHash($hash);

Expand All @@ -19,7 +23,7 @@ public function render()
file_put_contents($filepath, $minifiedJavascript);
}

return '@push("' . config('js-snippets.stack') . '")<script src="' . url(config('js-snippets.url') . '/' . $hash . '.js') . '"/>@endpush';
return '@push("' . config('js-snippets.stack') . '")<script src="' . url(config('js-snippets.url') . '/' . $hash . '.js') . '"/>' . PHP_EOL . '@endpush';
};
}
}

0 comments on commit cbc9d3f

Please sign in to comment.