I have project where I use a url in various places. To prevent having to change it in all places, I would like to define it as a constant value in just one place which is referenced everywhere. But I'm not sure what's "the way" to do this.
The value is the base url of where the assets of the site are hosted (it's different from the project url for various reasons) so in some places I have img elements like
<img src={`https://myassets.com/img/100/${imgNr}.jpg`} alt="" >
which I would like to replace by
<img src={`${ASSETS_HOST}/img/100/${imgNr}.jpg`} alt="" >
One way that comes to my mind is to define it in a script inside index.html before the main.js import, so it's available on top level in every file inside the Svelte part in src
, but I assume that's not the 'professional' way/place..? What are common ways to handle this?
consts.js
or similar file from which you import the relevant variables into every script that needs them. Adding globals to the window object as you suggest works, but it risks name clashes so it is usually avoided. Such globals also make the data flow less obvious, and make it more difficult to use linters or type checkers.