Donny P Donny P - 3 months ago 18
HTML Question

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

How can I have my

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

On development I want the
src
of my file to be an absolute path:
/dist/bundle.js


In production, I want the
src
of my file to be a relative path:
dist/bundle.js


Here is the HTML where the file is loaded:

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


If it is helpful, I am using Webpack.

Answer

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.