Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically adding SourceMap headers for JavaScript requests

I've started playing around with SourceMaps and am wondering if there's a way to automatically set the appropriate header automatically if a .map file exists for a JavaScript request using .htaccess instead of having to modify the original JavaScript file.

I already do something similar to serve minified JavaScript if it exists and I'm not debugging:

RewriteCond %{REQUEST_FILENAME}        \.(php|js)
RewriteRule .                          - [E=DEBUG:true]

RewriteCond %{ENV:DEBUG}               !^true$
RewriteCond %{REQUEST_URI}             ^(.+)\.js$
RewriteCond %{DOCUMENT_ROOT}%1-min.js  -f
RewriteRule .                          %1-min.js [L]

I guess it basically boils down to: how can I add an extra HTTP header if a certain file exists for a certain type of request?

UPDATE

The solution is as follows:

# If serving minified js and a SourceMap file exists, send appropriate header
RewriteCond %{REQUEST_URI}          ^(.+-min\.js)$
RewriteCond %{DOCUMENT_ROOT}%1.map  -f
RewriteRule .                       - [L,E=SOURCE_MAP:%{REQUEST_URI}.map]

Header set X-SourceMap "%{SOURCE_MAP}e" env=SOURCE_MAP
like image 607
Nev Stokes Avatar asked Jul 11 '26 18:07

Nev Stokes


1 Answers

See edit made by Nev Stokes above for the final solution

RewriteCond %{REQUEST_FILENAME}        \.(php|js)
RewriteRule .                          - [E=DEBUG:true]

RewriteCond %{ENV:DEBUG}               !^true$
RewriteCond %{REQUEST_URI}             ^(.+)\.js$
RewriteCond %{DOCUMENT_ROOT}%1-min.js  -f
RewriteRule [^/]+\.js$                 %1-min.js [L,E=SOURCE_MAP:%{REQUEST_URI}]

Header set X-SourceMap "%{SOURCE_MAP}e" env=SOURCE_MAP

I could not test the Header part as my test server doesn't have mod_headers installed.

like image 143
Gerben Avatar answered Jul 14 '26 07:07

Gerben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!