Get root route depending on dev and prod environment

Viewed 131

I would like to call script and css from site root.

  • I have a dev environment using wamp so my route is localhost/mysite/js/script.js.
  • My prod environment will be mysite/js/script.js.

I would like to call script from root, what should be the route if I'm not in the root folder and don't want to use ../?

The reason for that is I imagine a much more complex arborescence and I want to avoid excessive ../../../../[...] and I'm wondering if there is something for this.

Let's say I've a page in pages/contact.html and I want to call scripts/contact.js

  • If I call scripts/contact.js : 404 because I'm in the pages folder.
  • If I call /scripts/contact.js : It will work in mysite.com but won't in local because I need to call /mysite/scripts/contact.js.

Thanks for your help.

1 Answers

As @peter-krebs mentioned, the cleanest solution would be to spin up an isolated web server to develop this project in. You could use XAMPP as suggested but a containerized approach using Docker might be more flexible.

Alternatively, you can add a <base href="/mysite/"> tag to the head of all your pages and write all your paths as relative to that directory. You will have to specify all of your resource paths (js, css, images, links) using this relatively-absolute method though. Meaning you won't be able to directly access relative resources in the same directory anymore.

For example, if pages/contact.html needed the file pages/contact.js you could not use the path ./contact.js from within contact.html. You would have to specify pages/contact.js even though those files are in the same directory.

When you move the site to production, just change the base to <base href="/"> and everything will continue to work as expected. You could even do this in an automated way by adding the following script to your document head.

<!DOCTYPE html>
<html>
  <head>
    <script>
      let base = document.createElement('base');
      base.href = (document.location.host == 'localhost') ? '/mysite/' : '/';
      document.currentScript.replaceWith(base);
    </script>
    ...
Related