2

I want to send Javascript code over the wire and I don't want to use the full ScalaJS compiler for that. Let's assume this scenario in the backend:

I have a service that wants to define some validations for a textbox in the frontend. My frontend is written in Javascript and gets a Javascript function from the backend in json format and use that for validation.

I want to write that function in Scala in my backend and compile it to JS using ScalaJS and put it in json and send it to my frontend:

def validation(input: String): Boolean = {
   input.contains("scala is cool")
}

val jsFunctionText:Json = ScalaJSMagicCompiler.compileAndOptimizeFunction(validation)

reply(jsFunctionText)

Is there any way to do that? If not, what would be the best route to use the ScalaJS compiler to compile the function or a class and get a pointer to the output compiled file in the output folder or something?

I would rather do it at compile time but don't know if it's possible to have safe access to the generated code. something like this would be great:

@CompileAsJS("validation")
def validation(input: String): Boolean = {
   input.contains("scala is cool")
}

val jsFunctionText:Json = ScalaJSMagicCompiler.retrieveFromFile("validation", "output.jar")

reply(jsFunctionText)

1 Answer 1

1

I'm afraid you can't do that. Scala.js is designed to compile entire classpaths to JavaScript modules. You can't compile just one function. The main reason is that it preserves all the semantics of Scala, including the implementation of the collections, of strings, etc.

Of course in theory you could compile each such function as a module that exports only one function, and use that, but that would be way overkill, since it would bring the Scala.js "tax" on every function (a few KB minimum, but around 100 KB if you use anything from the collections).

Your use case was precisely the target of another project, namely JScala, but that project was discontinued.

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

2 Comments

Putting the ScalaJS "task" aside (imagine you can always ship the dependencies separately), is there any possible way to do it? If one wants to start something to do that, what would be the best path?
But you can't ship dependencies separately. Scala.js needs to generate the js for the entire program in one go. The best path forward for your use case is not to use Scala.js. It just isn't a solution for that use case, never was, and probably never will.

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.