Search code examples
javascripttemplatestemplate-literals

Define template strings as const to evaluate later


Is there a way to accomplish something like this:

const API_URL = `https://api.my-data-provider.com/items/${id}`

// [...]

// and later on or in another file, use it with something like
const result = await fetch(API_URL(id)) // or API_URL.apply(id), API_URL.apply({ id: 23}), etc...

I want to save template literals in a constants / configuration file, to use them later

Or is there any other standard or well established way to do this kind of thing?


Solution

  • You could use a function for this:

    const generateApiUrl = (id) => `https://api.my-data-provider.com/items/${id}`;
    const result = await fetch(generateApiUrl(id))