silvered.dragon
silvered.dragon

Reputation: 483

Make library available across entire svelte app

I'm Building my first app with svelte. Since I'm using axios to fetch data from my laravel api endpoint, I need to import axios across different components with some default settings, especially I need to import axios in some store files. What I did is to import inside my entry point app.svelte axios like this

<!-- App.svelte -->
        
<script>
// Axios
import axios from 'axios';
window.axios = axios;
        
// Axios defaults
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;
      
//....
</Script>

At this point I can use axios in all components and layouts across my app without importing again, but unfortunately if I call axios inside any store file, I will receive "error axios is undefined "and I have to import axios and defaults again in each store file. I tried to put the import and defaults inside main.js but is not working even from there, looks like store files are initialized before anything else or probably this is not the correct way to import common libraries. Any suggestion for this?

Upvotes: 0

Views: 133

Answers (1)

silvered.dragon
silvered.dragon

Reputation: 483

So at the end I understood that It's common pratice to import libraries in each file even if it feels repetitive, but in this particular case about axios, one good idea is to create an instance and add some defaults, so I created a file in my svelte project under /src/lib/defaults/axios.js like this

/**
 * AXIOS INSTANCE WITH DEFAULT SETTINGS FOR LARAVEL API ENDPOINTS 
 *
 **/ 
import axios from "axios";

const axiosDeafults = axios.create({

    baseURL: "http://192.168.25.73:8000",
    withCredentials: true,
    withXSRFToken: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
    }

});

export { axiosDeafults as axios };

then I can import axios with these defaults around my project using import in this way

import { axios } from '/src/lib/defaults/axios.js';

Upvotes: 1

Related Questions