I'm new to svelte and I'd like to use some environment variables like base_url in different components. I know that I can define store, and put those values there,like:
const Store = writable([
{
base_url: "http://127.0.0.1:8080",
}
]);
and each time I import store to compoenent using
let base_url = "";
import Store from "../stores/Store.js";
Store.subscribe((data) => {
base_url = data.base_url
});
But that involves lots of boilerplate code, and I find store more suitable for dynamic data rather than static values. So I'm wondering what is the more idomatic/convenient way to do so?
The way I mostly go about this is to create a file named environment.js or sth like that and put all my environment variables in there. Then I just need to import them where I need them.
// environment.js:
export const base_url = '..';
// somewhere-else.js/somecomponent.svelte:
import { base_url } from './path/to/environment.js';
This will also make it easier to replace these variables depending on whether you are in development or production mode. You can then easily add replacement solutions (replacing the variable value with what's fitting) which depend on what setup you use (Rollup: rollup-plugin-replace, Vite: env files, etc).
My structure is like this:
src/config/endpoint.js
//src/config/endpoint.js
let base_url = '';
switch(ENV){
case ENV_PROD:
base_url = 'http://www.example.com/api';
break;
case ENV_TEST:
base_url = 'http://www.example.com/test_api';
break;
default:
base_url = 'http://localhost:3301/api';
break;
}
export base_url;
Now import endpoint.js in your components or file and use like this:
//App.svelte
import { base_url } from './../config/endpoint.js';