1

I have a JS script script.js which contains a class MyType. I would like to use the class' methods add() and divide inside a scala script App.scala.

Using Scala.js and JSImport I import script.js into App.scala.

However when I try to use the MyType methods add() and divide inside the scala script, I get the error error: expected start of definition?

Could you please help me identify the problem?

Thanks in advance!

script.js:


class MyType {
    constructor(x, y) {

        this.x = x;
        this.y = y;

    }

    add(z){
        let {x,y} = this;
        return x + y + z;
    }

    divide(z){
        let {x,y} = this;
        return (x + y)/z;
    }
};

module.exports = {MyType};

App.scala:


import scala.scalajs.js
import scala.scalajs.js.annotation._

@js.native
@JSImport("./script.js","MyType")

class MyType(var x:Double, var y:Double) extends js.Object

object MyApp {
    @JSExport
    def main(args:Array[String]): Unit = {
        val added = new MyType(1,2).add(3)
        println(s"my $added") // 1

        val divided = new MyType(4,3).divide(2)
        println(s"my $divided") // 6
    }
}

build.scala:

name:="JSImports"
version:="0.1"
scalaVersion:="2.11.12"
enablePlugins(ScalaJSPlugin)
jsDependencies += ProvidedJS/"script.js"
scalaJSUseMainModuleInitializer:=true

3
  • 1
    What does your sbt (or other build tool) config look like? Commented Apr 23, 2022 at 7:24
  • Just updated the code to reflect the sbt build. Commented Apr 23, 2022 at 7:46
  • Your setup doesn't seem to make much sense to me. You use @JSImport, but your build does not seem to setup scalaJSLInkerConfig's withModuleKind(...), so linking should first emit an error saying that you haven't enabled module support. Also, using jsDependencies for something that is a JS module is not going to work. jsDependencies is an obsolete system that only handles Scripts. Commented Apr 23, 2022 at 11:05

1 Answer 1

0

The error expected start of definition is a result of a formatting mistake - you cannot have an empty line between @JSImport and class MyType.

This is most likely because of the way Scala is ending statements / declarations in the absence of semicolons. I do not know exact rules, but an empty line often makes a difference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.