Walter Chang
Walter Chang

Reputation: 11596

Unable to write a CommonJS module in ScalaJS that gets "imported" in Atom editor as a plugin

What should i do if i want to export some ScalaJS methods as CommonJS module? I have the following but it doesn't seem to work:

@ScalaJSDefined
@JSExportTopLevel("default")
object SourceFetch extends js.Object {
  def activate(state: js.Dynamic): Unit = {
    global.console.log("activate")
  }
  def deactivate(): Unit = {
    global.console.log("deactivate")
  }
}

And yes, scalaJSModuleKind := ModuleKind.CommonJSModule is in the build.sbt.

What i want as output is a commonjs module that looks like this;

export default {
  activate(state) {
    console.log("activate");
  }.
  deactivate() {
    console.log("deactivate");
  }
};

What i ended up doing is to use the deprecated sbt key "scalaJSOutputWrapper" and append 'module.exports = exports["default"];' at the end of output JS file.

I did try "scalaJSUseMainModuleInitializer" but I am only able to get a hold of "module.exports" not "exports" and the value of "module.exports" is undefined.

Upvotes: 0

Views: 163

Answers (1)

sjrd
sjrd

Reputation: 22085

Your above snippet does indeed correspond to the piece of ECMAScript 2015 code that you wrote. However, that does not export the methods as direct members of the module, but as members of the default object. And no, the default export is not the same as the module itself (although many people think so).

To export the functions as direct members of the module, you should write:

object SourceFetch {
  @JSExportTopLevel("activate")
  def activate(state: js.Dynamic): Unit = {
    global.console.log("activate")
  }
  @JSExportTopLevel("deactivate")
  def deactivate(): Unit = {
    global.console.log("deactivate")
  }
}

Upvotes: 1

Related Questions