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?

  • 2
    There is no "one way" to do this. It is a subjective question. For things like this, consult your team so you can all agree on where to do these things. If you added more information about how this URL is used and some more information about the architecture, this might be something we can answer. Commented May 6, 2022 at 15:11
  • 3
    It is common to have a 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.
    – amon
    Commented May 6, 2022 at 15:22
  • @GregBurghardt Would love to ask the team, but unfortunately there's none - it's just me :) I added the info about the url - not sure what you mean by the architecture...
    – Corrl
    Commented May 6, 2022 at 17:21
  • @amon Thanks, good to know that!
    – Corrl
    Commented May 6, 2022 at 17:26


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.