javascriptnode.jsscalascala.js

Scala.js import JS script gives error: expected start of definition


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


Solution

  • 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.