Home > Blockchain >  What is the correct way to import a js class into a Svelte component?
What is the correct way to import a js class into a Svelte component?

Time:06-18

I have a SomeClass.ts like:

class SomeClass {
  constructor () {
    console.log('created someclass')
  }
}

export default SomeClass

Which compiles to SomeClass.js

'use strict'
exports.__esModule = true
const SomeClass = /** @class */ (function () {
  function SomeClass () {
    console.log('created someclass')
  }
  return SomeClass
}())
exports.default = SomeClass

And is imported into the script tag of App.svelte like:

<script>
  import SomeClass from "./SomeClass";

  const instance = new SomeClass();
</script>

But when running the app I get error:

Uncaught SyntaxError: import not found: default

on generated line: import SomeClass from "/src/SomeClass.js?t=1655451078055";

Note:

Just using regular ES6 flavour class & export default MyClass in SomeClass.js works fine, but might as well just remove Typescript...


Installed svelte-preprocess

npm install -D svelte-preprocess

Updated vite.config.js like so:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import sveltePreprocess from 'svelte-preprocess' // <--- added this

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte({
    preprocess: sveltePreprocess() // <--- added this
  })]
})

Deleted the compiled .js and now just work with the Typescript file directly no problems!

enter image description here

CodePudding user response:

The class is compiled with a different module system (CommonJS) than what is expected by Svelte (ES module).

I would not recommend compiling the class separately but instead to use svelte-preprocess and import/use the TypeScript source directly in the component, by using a <script lang="ts"> tag. Then the class should be compiled alongside the component code.

If the class is not used anywhere else you could probably also change the module option to "esnext" in the corresponding tsconfig.json.

  • Related