Donny P Donny P - 1 year ago 67
HTML Question

Have an HTML load a JS file from different places, depending on environment

How can I have my

load a JS file from different places, depending on my environment?

On development I want the
of my file to be an absolute path:

In production, I want the
of my file to be a relative path:

Here is the HTML where the file is loaded:

<!doctype html>
<title>Sample App</title>
<div id='root'>
<script src="/dist/bundle.js"></script>

If it is helpful, I am using Webpack.

Answer Source

You've mentioned that webpack is being used, I'm assuming a different configuration is used for development and production.

You could try the html-webpack-plugin and set it up to inject the script in your index.html file. This way the script will be injected into HTML based on the webpack output setup. You might have to adjust your config accordingly. If that doesn't work, the webpack-path-rewriter seems as an option too, but I haven't tried it yet.

Or you could write a small script that would determine the environment based on document.location.hostname and then include a <script> with correct src path. But this approach just doesn't seem right and is prone to changing domains.

But I would agree with what @Makyen, make environments the same. I assume the production one would be more difficult to change, so try to match that one with whatever you're doing in development.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download