简体   繁体   中英

export function to global scope in scalajs

Question about scalajs and javascript.

How to mark a function to be purely exported to global scope?

Given scala object in top level package

@JSExport
object Foo{
 def apply(a: Int, b: Int): String = "bar"+a+b
}

I would like to compile this scala code into javascript and have this function named Foo in global scope. In other words I would like to have a javascript similar to this:

function Foo(a,b) {
    return 'bar'+a+b;
}

Is it possible using scalajs?

I am writing component in javascript, which will be referenced from third party API which can not be influenced by me. This is why I simply need to follow their rules and provide javascript functions in global scope.

The solution to this is now Top Level Exports, as documented under the now-closed issue #1381 - to use this feature, tag a function in an object with @JSExportTopLevel .

object A {
  @JSExportTopLevel("foo")
  def foo(x: Int): Int = x + 1
}

<Foo will be available from JavaScript's global namespace>

(See https://www.scala-js.org/doc/interoperability/export-to-javascript.html for the official documentation, under "Exporting top-level methods".)

You currently cannot do this without executing some code. But you can have setup code that assigns it:

import scala.scalajs.js

object App extends js.JSApp {
  def main(): Unit = {
    js.Dynamic.global.anything = // your js.FunctionN

  }
}

There is an issue open ( #1381 ) to have language support for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM