We assume that you have an existing Vite and Scala.js sbt project. If not,follow the accompanying tutorial.
Install the plugin as a development dependency:
$ npm install -D @scala-js/vite-plugin-scalajs
Tell Vite to use the plugin invite.config.js
:
import{defineConfig}from"vite";
importscalaJSPluginfrom"@scala-js/vite-plugin-scalajs";
exportdefaultdefineConfig({
plugins:[scalaJSPlugin()],
});
Finally, import the Scala.js output from a.js
or.ts
file with
import'scalajs:main.js';
which will execute the main method of the Scala.js application.
The sbt project must at least be configured to use ES modules.
For the best feedback loop with Vite, we recommend to emit small modules for application code.
If your application lives in themy.app
package, configure the sbt project with the following settings:
scalaJSLinkerConfig~={
_.withModuleKind(ModuleKind.ESModule)
.withModuleSplitStyle(
ModuleSplitStyle.SmallModulesFor(List("my.app")))
},
In development mode, use two terminals in parallel:
- One with
$ npm run dev
. - One with
$ sbt '~fastLinkJS'
(or a more precise version such as$ sbt '~theJSProject/fastLinkJS
).
For the production build,$ npm run build
is enough.
The plugin supports the following configuration options:
exportdefaultdefineConfig({
plugins:[
scalaJSPlugin({
// path to the directory containing the sbt build
// default: '.'
cwd:'.',
// sbt project ID from within the sbt build to get fast/fullLinkJS from
// default: the root project of the sbt build
projectID:'client',
// URI prefix of imports that this plugin catches (without the trailing ':')
// default: 'scalajs' (so the plugin recognizes URIs starting with 'scalajs:')
uriPrefix:'scalajs',
}),
],
});
@JSExportTopLevel( "foo" )
members in the Scala.js code are exported from the modules that Scala.js generates.
They can be imported in.js
and.ts
files with the usual JavaScriptimport
syntax.
For example, given the following Scala.js definition:
importscala.scalajs.js
importscala.scalajs.js.annotation._
@JSExportTopLevel("ScalaJSLib")
classScalaJSLibextendsjs.Object{
defsquare(x:Double):Double=x*x
}
we can import and use it as
import{ScalaJSLib}from'scalajs:main.js';
constlib=newScalaJSLib();
console.log(lib.square(5));// 25
By default,@JSExportTopLevel( "Foo" )
exportsFoo
from themain
module, which is why we import fromscalajs:main.js
.
We can also split the Scala.js exports into several modules.
For example,
importscala.scalajs.js
importscala.scalajs.js.annotation._
@JSExportTopLevel("ScalaJSLib","library")
classScalaJSLibextendsjs.Object{
defsquare(x:Double):Double=x*x
}
can be imported with
import{ScalaJSLib}from'scalajs:library.js';
The Scala.js documentation containsmore information about module splitting.