3 namespace Drupal\Core\Asset;
5 use Drupal\Component\Utility\Unicode;
8 * Optimizes a JavaScript asset.
10 class JsOptimizer implements AssetOptimizerInterface {
15 public function optimize(array $js_asset) {
16 if ($js_asset['type'] !== 'file') {
17 throw new \Exception('Only file JavaScript assets can be optimized.');
19 if (!$js_asset['preprocess']) {
20 throw new \Exception('Only file JavaScript assets with preprocessing enabled can be optimized.');
23 // If a BOM is found, convert the file to UTF-8, then use substr() to
24 // remove the BOM from the result.
25 $data = file_get_contents($js_asset['data']);
26 if ($encoding = (Unicode::encodingFromBOM($data))) {
27 $data = mb_substr(Unicode::convertToUtf8($data, $encoding), 1);
29 // If no BOM is found, check for the charset attribute.
30 elseif (isset($js_asset['attributes']['charset'])) {
31 $data = Unicode::convertToUtf8($data, $js_asset['attributes']['charset']);
34 // No-op optimizer: no optimizations are applied to JavaScript assets.
39 * Processes the contents of a javascript asset for cleanup.
41 * @param string $contents
42 * The contents of the javascript asset.
45 * Contents of the javascript asset.
47 public function clean($contents) {
48 // Remove JS source and source mapping urls or these may cause 404 errors.
49 $contents = preg_replace('/\/\/(#|@)\s(sourceURL|sourceMappingURL)=\s*(\S*?)\s*$/m', '', $contents);