Search code examples
javascriptsveltesvelte-3

How to import js file into svelte


I am building an app in svelte and I have a helper.js file inside /src folder where I am going to put helper functions.

I am trying to import the helper.js file into the GetData.svelte file:

GateData.svelte:

<script>
  import Helper from "./helper.js";

  let helper = new Helper();

</script>

helper.js:

class Helper {
    constructor() {
        console.log("hello world");
    }
}

main.js:

import App from './App.svelte';


const app = new App({
    target: document.body,
});

export default app;

However, the error message I get is:

==>> Uncaught ReferenceError: Helper is not defined (main.js 6)

Do I have to import the helper.js file in the main.js as well?

Thank you for any help.


Solution

  • You need to export your class in helper.js:

    export class Helper {
        // ...
    }
    

    and then import it in main.js as

    import { Helper } from "./helper.js";
    

    Or, if you only want to export this one class from the helper file, you can use

    export default class Helper {
        // ...
    }
    

    and import as you currently do:

    import Helper from "./helper.js";