Is it possible to access Svelte store from external js files?

Yes, absolutely.

For one thing, the store API is very simple and nothing prevents you from subscribing to the store yourself to know the value:

import myStore from './stores'

myStore.subscribe(value => {
  // do something with the new value
  // you could store it for future reference...
})

And, if you just want to know the current value, Svelte has a helper for that, the get function:

import { get } from 'svelte/store';

import myStore from './stores'

const value = get(myStore);

In addition to rixo's answer, a better way to implement add is to use the store's update method:

import { counter } from "./stores";

export function add() {
    counter.update(n => n + 1);
}

You could also create a custom store that implemented that logic.


It's not exactly what you asked for (import) but this method serves same purpose: you pass your store as argument, so no need to import in the .js your store

import {get} from 'svelte/store'
export function add(yourStore) {
   let _yourStore = get(yourStore)
   yourStore.set(_yourStore + 1)
}

Then you just have to import your store in your Svelte component.
It allows not to care about store imports in your .js, but only on your component.