PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] What is the correct way to import a js class into a Svelte component?

 August 24, 2022     import, javascript, module, svelte, typescript     No comments   

Issue

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


Solution

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.



Answered By - H.B.
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing