Import function from js file into svelte but variable is not defined

I would like to import a function from a js file into App.svelte. The function includes a variable c that is not defined in the js file. C changes values but I don’t want my function to be reactive to the change in c, only reactive to the change in b. When b changes my funcion should use whatever the value of c is. When I define the function in the app.svelte it works but not with the import.

How can I accomplish that?

Here is a repl:


    import {sum} from './function.js'
    let a = 1;
    let b = 2;
    let c = 3;
    let res;
    $: res = sum(a, b);

<button on:click={() => c=c+1}>
<button on:click={() => b=b+1}>
export function sum(a, b) {
    return a + b + c

>Solution :

You could curry it:

export const sum = c => (a, b) => a + b + c;
import { sum } from './function.js';

// ...
const c = 3;
const sumWithC = sum(c);
$: res = sumWithC(a, b);

(Extracting such a basic function probably does not make much sense, though.)

Leave a Reply