### Install Dependencies and Run Development Server
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Commands to navigate into the project directory, install necessary npm packages, and start the Vite development server.
```shell
$ cd livechart
$ npm install
[...]
$ npm run dev
VITE v4.1.4 ready in 156 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h to show help
```
--------------------------------
### Docker Setup for Scala.js Website
Source: https://github.com/scala-js/scala-js-website/blob/main/README.md
This snippet demonstrates how to start the Scala.js website development environment using Docker Compose. It covers initial build and rebuild commands, and notes the default access URL.
```bash
docker compose up --build
```
```bash
docker compose build --no-cache
```
--------------------------------
### Preview Production Build
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Starts a local HTTP server to preview the production-ready static files generated by the build process.
```shell
$ npm run preview
> livechart@0.0.0 preview
> vite preview
➜ Local: http://localhost:4173/
➜ Network: use --host to expose
```
--------------------------------
### Manual Ruby Tooling Setup for Scala.js Website
Source: https://github.com/scala-js/scala-js-website/blob/main/README.md
This section outlines the steps to set up the Scala.js website development environment manually using Ruby tooling, specifically Jekyll. It includes installing RVM, Ruby, Bundler, and Jekyll dependencies, as well as commands for building and serving the site with live watch.
```bash
rvm use 2.7.5 --install
gem install bundler
bundle install
bundle exec jekyll build
```
```bash
bundle exec jekyll serve --watch
```
--------------------------------
### Install Vite Scala.js Plugin
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Installs the necessary Vite plugin for Scala.js integration as a development dependency.
```shell
$ npm install -D @scala-js/vite-plugin-scalajs@1.0.0
```
--------------------------------
### JavaScript Asset Import Example (JavaScript)
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Illustrates the standard JavaScript syntax for importing static assets, which is then translated to Scala.js.
```javascript
import javascriptLogo from "/javascript.svg"
```
--------------------------------
### Main JavaScript Entry Point
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Sets up the main JavaScript file to import CSS and the Scala.js application entry point.
```javascript
import './style.css'
import 'scalajs:main.js'
```
--------------------------------
### sbt Build Configuration
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Configuration files for an sbt build, specifying the sbt version and enabling the sbt-scalajs plugin.
```plaintext
sbt.version=1.10.0
```
--------------------------------
### Bootstrap Vite Project
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Command to create a new Vite project using the vanilla JavaScript template. This sets up the basic structure for a web application.
```shell
$ npm create vite@4.1.0
Need to install the following packages:
create-vite@4.1.0
Ok to proceed? (y)
✔ Project name: … livechart
✔ Select a framework: › Vanilla
✔ Select a variant: › JavaScript
Scaffolding project in .../livechart...
Done. Now run:
cd livechart
npm install
npm run dev
```
--------------------------------
### Production Build Command
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Executes the production build command for the Vite project, which optimizes and bundles the application.
```shell
$ npm run build
> livechart@0.0.0 build
> vite build
vite v4.1.4 building for production...
[info] welcome to sbt 1.8.0 (Temurin Java 1.8.0_362)
[...]
[info] Full optimizing .../livechart/target/scala-3.2.2/livechart-opt
.../livechart/target/scala-3.2.2/livechart-opt
✓ 11 modules transformed.
dist/index.html 0.45 kB
dist/assets/javascript-8dac5379.svg 1.00 kB
dist/assets/index-48a8825f.css 1.24 kB │ gzip: 0.65 kB
dist/assets/index-3c83baa6.js 28.84 kB │ gzip: 6.97 kB
```
--------------------------------
### Install source-map-support with npm
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Installs the `source-map-support` npm package locally for the project to enable stack trace resolution in Node.js.
```bash
$ npm init private
$ npm install source-map-support
```
--------------------------------
### Verify Development Tools Installation
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/index.md
This snippet demonstrates how to verify the installation of essential development tools like Node.js, npm, and sbt by executing their version commands in a terminal.
```shell
$ node -v
v16.13.0
$ npm -v
8.1.0
$ sbt -version
sbt version in this project: 1.7.3
sbt script version: 1.7.3
```
--------------------------------
### sbt Build Command
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
The command to execute within the sbt shell to build the Scala.js project and generate the fastLinkJS output.
```shell
~fastLinkJS
```
--------------------------------
### Starting sbt with a Specific Scala.js Version
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2019-12-13-announcing-scalajs-1.0.0-RC2.md
Command-line example demonstrating how to launch sbt with a specific Scala.js version (e.g., 1.0.0-RC2) by setting the `SCALAJS_VERSION` environment variable.
```bash
$SCALAJS_VERSION=1.0.0-RC2 sbt
```
--------------------------------
### Dockerized Scala.js Example with Akka HTTP and Postgres
Source: https://github.com/scala-js/scala-js-website/blob/main/libraries/skeletons.md
A minimal yet complete web application example using Scala.js with Akka HTTP as the backend and Postgres as the database. The application is dockerized for easy setup.
```Scala
This is a link to an example project: https://gitlab.com/bullbytes/scala-js-example
```
--------------------------------
### Create New Scala.js Project
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/hello-world.md
Creates a new Scala.js project named 'hello-scalajs' using the 'scalajs_hello_world' template via the Activator build tool.
```bash
activator new hello-scalajs scalajs_hello_world
```
--------------------------------
### Vite Configuration for Scala.js
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Configures Vite to use the Scala.js plugin by importing and including it in the plugins array.
```javascript
import { defineConfig } from "vite";
import scalaJSPlugin from "@scala-js/vite-plugin-scalajs";
export default defineConfig({
plugins: [scalaJSPlugin()],
});
```
--------------------------------
### Install jsdom
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Install the jsdom library using npm, which is required by the JSDOMNodeJSEnv to simulate the DOM environment for your Scala.js application.
```bash
$ npm install jsdom
```
--------------------------------
### Main sbt Build File
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
The primary sbt build configuration file for a Scala.js project. It enables the Scala.js plugin, sets the Scala version, configures Scala.js to use main module initializers, optimizes module splitting for Vite, and adds the scalajs-dom library as a dependency.
```scala
import org.scalajs.linker.interface.ModuleSplitStyle
lazy val livechart = project.in(file("."))
.enablePlugins(ScalaJSPlugin) // Enable the Scala.js plugin in this project
.settings(
scalaVersion := "3.3.3",
// Tell Scala.js that this is an application with a main method
scalaJSUseMainModuleInitializer := true,
/* Configure Scala.js to emit modules in the optimal way to
* connect to Vite's incremental reload.
* - emit ECMAScript modules
* - emit as many small modules as possible for classes in the "livechart" package
* - emit as few (large) modules as possible for all other classes
* (in particular, for the standard library)
*/
scalaJSLinkerConfig ~= {
_.withModuleKind(ModuleKind.ESModule)
.withModuleSplitStyle(
ModuleSplitStyle.SmallModulesFor(List("livechart")))
},
/* Depend on the scalajs-dom library.
* It provides static types for the browser DOM APIs.
*/
libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "{{ site.versions.scalaJSDOM }}",
)
```
--------------------------------
### Update UI Message
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Shows a diff of the HTML file, illustrating a change to the displayed message from 'Hello Scala.js!' to 'Hello Scala.js and Vite!'.
```diff
-
Hello Scala.js!
+
Hello Scala.js and Vite!
```
--------------------------------
### Hello World Examples
Source: https://github.com/scala-js/scala-js-website/blob/main/index.html
Demonstrates the 'Hello World!' output in various languages including JavaScript, ECMAScript 6, TypeScript, and Scala.js.
```javascript
console.log("Hello World!");
```
```ecmascript6
console.log("Hello World!");
```
```typescript
console.log("Hello World!");
```
```scala
println("Hello World!")
```
--------------------------------
### Update HTML Content
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Demonstrates a code change in the `main.js` file to update the heading text from 'Hello Vite!' to 'Hello Scala.js!'. This change is reflected instantly in the browser due to Vite's live-reloading.
```diff
-
Hello Vite!
+
Hello Scala.js!
```
--------------------------------
### JavaScript Asset Import in Scala.js
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Demonstrates how to import static assets like SVG files in Scala.js, mirroring JavaScript's import syntax for use with bundlers like Vite.
```scala
@js.native @JSImport("/javascript.svg", JSImport.Default)
val javascriptLogo: String = js.native
```
--------------------------------
### Install Node.js using nvm
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/project/js-environments.md
Installs a specific version of Node.js on Ubuntu using the Node Version Manager (nvm).
```bash
nvm install 5.0
```
--------------------------------
### Scala.js Main Application Code
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
The main Scala.js application code that interacts with the browser DOM. It sets up the HTML content for an element with the ID 'app', includes Vite and JavaScript logos, displays a counter, and sets up an event listener to increment the counter.
```scala
package livechart
import scala.scalajs.js
import scala.scalajs.js.annotation.*
import org.scalajs.dom
// import javascriptLogo from "/javascript.svg"
@js.native @JSImport("/javascript.svg", JSImport.Default)
val javascriptLogo: String = js.native
@main
def LiveChart(): Unit =
dom.document.querySelector("#app").innerHTML = s"""
Hello Scala.js!
Click on the Vite logo to learn more
"
setupCounter(dom.document.getElementById("counter"))
end LiveChart
def setupCounter(element: dom.Element): Unit =
var counter = 0
def setCounter(count: Int): Unit =
counter = count
element.innerHTML = s"count is $counter"
element.addEventListener("click", e => setCounter(counter + 1))
setCounter(0)
end setupCounter
```
--------------------------------
### Upgrade Commit Example
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2014-12-05-announcing-scalajs-0.6.0-M2.md
Provides a reference to a git commit that illustrates the necessary changes for upgrading a Scala.js project from 0.5.x to 0.6.x.
```git
https://github.com/sjrd/scala-js-example-app/commit/fdc2b9c2dedcbcf64086b11b74e980cfe0792847
```
--------------------------------
### Scala.js JUnit Integration Example
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2016-01-25-announcing-scalajs-0.6.6.md
Example demonstrating how to enable JUnit testing for a Scala.js project, including cross-project configuration. It shows how to enable the `ScalaJSJUnitPlugin` for the JS variant and add the JUnit dependency for the JVM variant.
```scala
lazy val myCrossProject = crossProject.
jsConfigure(_.enablePlugins(ScalaJSJUnitPlugin)).
jvmSettings(
libraryDependencies +=
"com.novocode" % "junit-interface" % "0.9" % "test"
)
```
--------------------------------
### Start SBT with Specific Scala.js Version
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2019-06-03-announcing-scalajs-1.0.0-M8.md
Launches the sbt build environment with a specified Scala.js version by setting the SCALAJS_VERSION environment variable.
```bash
$ SCALAJS_VERSION=1.0.0-M8 sbt
```
--------------------------------
### Start Vite Development Server
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/laminar.md
This command starts Vite's development server, which is used to serve the Scala.js application during development. It allows for hot module replacement and efficient development workflows.
```shell
$ npm run dev
[...]
```
--------------------------------
### Production HTML Structure
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
An example HTML file structure for a Scala.js application, including the script tag to include the fully optimized JavaScript code.
```html
The Scala.js Tutorial
```
--------------------------------
### JavaScript Chart.js Configuration Equivalent
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalablytyped.md
The equivalent Chart.js configuration written in plain JavaScript, demonstrating the structure and options used in the Scala.js example.
```javascript
{
type: "bar",
data: {
datasets: [
{
label: "Price",
borderWidth: 1,
backgroundColor: "green"
},
{
label: "Full price",
borderWidth: 1,
backgroundColor: "blue"
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
```
--------------------------------
### Run Scala.js Application
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/hello-world.md
Navigates into the project directory and runs the Scala.js application using the Activator build tool. The first run may take time due to package downloads.
```bash
cd hello_scalajs
activator run
```
--------------------------------
### Play Scala.js Workbench Example
Source: https://github.com/scala-js/scala-js-website/blob/main/libraries/skeletons.md
An example setup using the Scala.js Workbench plugin with Play Framework. This setup prevents client code changes from causing compile errors on the Play server, thus speeding up client development.
```Scala
This is a link to an example project: https://github.com/aholland/play-scalajs-workbench-example
```
--------------------------------
### sbt Plugin Declaration
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalajs-vite.md
Declares the sbt-scalajs plugin in the sbt build configuration.
```scala
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "{{ site.versions.scalaJS }}")
```
--------------------------------
### SBT Commands for Testing and Optimization
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Demonstrates common sbt commands used in Scala.js projects for running tests and performing full optimizations.
```bash
> test
[info] Compiling 1 Scala source to (...)/scalajs-tutorial/target/scala-2.13/test-classes...
[info] Fast optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-test-fastopt
-------------------------------- Running Tests --------------------------------
+ tutorial.webapp.TutorialTest.HelloWorld 3ms
+ tutorial.webapp.TutorialTest.ButtonClick 6ms
Tests: 2, Passed: 2, Failed: 0
[success] Total time: 15 s, completed 16-mars-2018 20:07:33
```
```bash
> fullLinkJS
[info] Full optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-opt
[info] Closure: 0 error(s), 0 warning(s)
[success] (...)
```
```bash
> set scalaJSStage in Global := FullOptStage
```
--------------------------------
### Basic sbt Project Setup
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Configures a new sbt project for Scala.js, enabling the ScalaJSPlugin, setting the project name, Scala version, and enabling the main module initializer for applications with a main method.
```scala
enablePlugins(ScalaJSPlugin)
name := "Scala.js Tutorial"
scalaVersion := "2.13.14" // or a newer version such as "3.4.2", if you like
// This is an application with a main method
scalaJSUseMainModuleInitializer := true
```
--------------------------------
### Scala.js Hello World Application
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
A simple Scala.js object with a `main` method that prints 'Hello world!' to the console. This serves as the initial application code.
```scala
package tutorial.webapp
object TutorialApp {
def main(args: Array[String]): Unit = {
println("Hello world!")
}
}
```
--------------------------------
### Create a Simple uTest Test Suite
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Define a test suite in Scala.js using uTest. This example demonstrates how to initialize the application and write a basic test that asserts the presence and content of a DOM element.
```scala
package tutorial.webapp
import utest._
import scala.scalajs.js
import org.scalajs.dom
import org.scalajs.dom.document
import org.scalajs.dom.ext._
object TutorialTest extends TestSuite {
// Initialize App
TutorialApp.setupUI()
def tests = Tests {
test("HelloWorld") {
assert(document.querySelectorAll("p").count(_.textContent == "Hello World") == 1)
}
}
}
```
--------------------------------
### Setting up UI on DOMContentLoaded in Scala.js
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Sets up the application's user interface by listening for the 'DOMContentLoaded' event. This ensures that the UI elements are created and manipulated only after the HTML document has been fully loaded and parsed.
```scala
def main(args: Array[String]): Unit = {
document.addEventListener("DOMContentLoaded", { (e: dom.Event) =>
setupUI()
})
}
def setupUI(): Unit = {
val button = document.createElement("button")
button.textContent = "Click me!"
button.addEventListener("click", { (e: dom.MouseEvent) =>
addClickedMessage()
})
document.body.appendChild(button)
appendPar(document.body, "Hello World")
}
```
--------------------------------
### XMLHttpRequest Example (JavaScript vs Scala.js)
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/sjs-for-js/index.md
Demonstrates the implementation of an XMLHttpRequest to fetch data from the Twitter API in both JavaScript ES6 and Scala.js. It shows how to open a GET request, handle the response, parse JSON, and update the DOM.
```javascript
const xhr = new XMLHttpRequest();
xhr.open("GET",
"https://api.twitter.com/1.1/search/" +
"tweets.json?q=%23scalajs"
);
xhr.onload = (e) => {
if (xhr.status === 200) {
const r = JSON.parse(xhr.responseText);
$("#tweets").html(parseTweets(r));
}
};
xhr.send();
```
```scala
val xhr = new XMLHttpRequest()
xhr.open("GET",
"https://api.twitter.com/1.1/search/" +
"tweets.json?q=%23scalajs"
)
xhr.onload = { (e: Event) =>
if (xhr.status == 200) {
val r = JSON.parse(xhr.responseText)
$("#tweets").html(parseTweets(r))
}
}
xhr.send()
```
--------------------------------
### Conditional sbt Dependencies for JS Environments
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2018-08-13-announcing-scalajs-1.0.0-M5.md
Provides examples of how to conditionally add sbt dependencies for JavaScript environments like `scalajs-env-jsdom-nodejs` and `scalajs-env-phantomjs` based on the Scala.js version. This ensures compatibility and proper setup for different testing or runtime environments.
```scala
// For Node.js with jsdom
libraryDependencies ++= {
if (scalaJSVersion.startsWith("0.6.")) Nil
else Seq("org.scala-js" %% "scalajs-env-jsdom-nodejs" % "1.0.0-M5")
}
// For PhantomJS
{
if (scalaJSVersion.startsWith("0.6.")) Nil
else Seq(addSbtPlugin("org.scala-js" % "sbt-scalajs-env-phantomjs" % "1.0.0-M5"))
}
```
--------------------------------
### Scala.js WebAssembly Backend Setup
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2024-09-28-announcing-scalajs-1.17.0.md
Configuration for enabling the experimental WebAssembly backend in Scala.js. This involves setting linker configurations and Node.js environment arguments for WebAssembly features.
```scala
scalaJSLinkerConfig := {
scalaJSLinkerConfig.value
.withExperimentalUseWebAssembly(true) // use the Wasm backend
.withModuleKind(ModuleKind.ESModule) // required by the Wasm backend
},
// Configure Node.js (at least v22) to support the required Wasm features
jsEnv := {
val config = NodeJSEnv.Config()
.withArgs(List(
"--experimental-wasm-exnref", // required
"--experimental-wasm-imported-strings", // optional (good for performance)
"--turboshaft-wasm", // optional, but significantly increases stability
))
new NodeJSEnv(config)
}
```
--------------------------------
### Scala.js Dependency Example
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2014-12-22-announcing-scalajs-0.6.0-M3.md
Example of how to declare a dependency on scalajs-jquery for Scala.js 0.6.0-M3.
```scala
"be.doeraene" %%% "scalajs-jquery" % "0.7.0"
```
--------------------------------
### Scala.js Wasm Backend Setup
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/project/webassembly.md
Configures the Scala.js build to use the experimental WebAssembly backend and sets up the Node.js environment with necessary experimental flags for Wasm features.
```scala
scalaJSLinkerConfig := {
scalaJSLinkerConfig.value
.withExperimentalUseWebAssembly(true) // use the Wasm backend
.withModuleKind(ModuleKind.ESModule) // required by the Wasm backend
},
// Configure Node.js (at least v23) to support the required Wasm features
jsEnv := {
val config = NodeJSEnv.Config()
.withArgs(List(
"--experimental-wasm-exnref", // always required
"--experimental-wasm-jspi", // required for js.async/js.await
"--experimental-wasm-imported-strings", // optional (good for performance)
"--turboshaft-wasm", // optional, Node.js 23.x.x only, but significantly increases stability
))
new NodeJSEnv(config)
}
```
--------------------------------
### Scala.js Node.js Starter (npm)
Source: https://github.com/scala-js/scala-js-website/blob/main/libraries/skeletons.md
A Scala.js skeleton application for Node.js environments, managed with npm commands. It supports commands like 'npm start', 'build', 'test', and 'clean'.
```Scala
This is a link to an example project: https://github.com/konradst/scalajs-starter
```
--------------------------------
### Cross-building Scala.js: Launching sbt with a Specific Version
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2017-11-29-announcing-scalajs-1.0.0-M2.md
Shows the command-line usage for launching sbt with a specific Scala.js version set via an environment variable, facilitating cross-building efforts.
```bash
$ SCALAJS_VERSION=1.0.0-M2 sbt
```
--------------------------------
### Scala.js Linking Error Example
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/project/linking-errors.md
An example of a typical linking error message encountered during Scala.js compilation, indicating a reference to a non-existent method or class.
```text
[info] Fast optimizing .../helloworld/target/scala-2.12/helloworld-fastopt
[error] Referring to non-existent method scala.concurrent.impl.Promise$CompletionLatch.releaseShared(scala.Int)scala.Boolean
[error] called from scala.concurrent.impl.Promise$CompletionLatch.apply(scala.util.Try)scala.Unit
[error] called from scala.concurrent.impl.Promise$CompletionLatch.apply(java.lang.Object)java.lang.Object
[error] ...
[error] There were linking errors
[error] (helloworld/compile:fastLinkJS) There were linking errors
[error] Total time: 2 s, completed Sep 13, 2019 1:30:39 PM
```
--------------------------------
### Output of Dynamic Greeter Example
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2017-11-29-announcing-scalajs-1.0.0-M2.md
The expected output when running the Scala.js code that dynamically creates JavaScript greeter classes and uses them via a JavaScript function.
```text
Hello, Jane!
Hello, John!
Bonjour, Jane!
Bonjour, John!
Janeさん、こんにちは。
Johnさん、こんにちは。
```
--------------------------------
### sbt Version Configuration
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/basic/index.md
Specifies the sbt version to be used for the project in the `project/build.properties` file.
```scala
sbt.version=1.7.1
```
--------------------------------
### Play Application with Scala.js Example
Source: https://github.com/scala-js/scala-js-website/blob/main/libraries/skeletons.md
An example application demonstrating the integration of Play Framework with Scala.js. This skeleton provides a foundation for building web applications using both technologies.
```Scala
This is a link to an example project: https://github.com/vmunier/play-with-scalajs-example
```
--------------------------------
### Scala.js Dynamic Import Example
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/project/module.md
Illustrates the usage of `js.dynamicImport` to load a feature asynchronously. This example shows how a heavy computation is deferred until a button click, improving the initial load time.
```scala
import scala.scalajs.js
import scala.scalajs.js.annotation._
import scala.concurrent.ExecutionContext.Implicits.global
class HeavyFeature {
def doHeavyFeature(x: Int): Int =
x * 2
}
object MyApp {
@JSExportTopLevel(name = "onClick")
def onClick(input: Int): Unit = {
val resultPromise: js.Promise[Int] = js.dynamicImport {
new HeavyFeature().doHeavyFeature(input)
}
for (result <- resultPromise.toFuture)
updateUIWithOutput(result)
}
private def updateUIWithOutput(i: Int): Unit = ???
}
```
--------------------------------
### Running Scalafix
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2017-03-21-announcing-scalajs-0.6.15.md
Command to execute scalafix for code migration.
```bash
$ sbt scalafix
```
--------------------------------
### Incremental Compilation Error Example
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/project/linking-errors.md
This code snippet shows an example of a compiler error related to incremental compilation issues in Scala.js. It indicates that a method is being referred to but does not exist, often due to out-of-sync compiled files.
```scala
[error] Referring to non-existent method helloworld.Foo.bar(java.lang.String)scala.Unit
[error] called from helloworld.HelloWorld$.main()scala.Unit
[error] called from core module module initializers
[error] involving instantiated classes:
[error] helloworld.HelloWorld$
[error] There were linking errors
```
--------------------------------
### SPA Tutorial with Scala.js and React
Source: https://github.com/scala-js/scala-js-website/blob/main/libraries/skeletons.md
A simple Single Page Application tutorial built using scalajs-react, Play Framework, and Bootstrap. This provides a basic structure for creating SPAs with Scala.js.
```Scala
This is a link to an example project: https://github.com/ochrons/scalajs-spa-tutorial
```
--------------------------------
### Fast Linking for JavaScript Output
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/project/building.md
Performs fast Scala.js-specific optimizations and generates a single JavaScript file (e.g., main.js) in the target directory with a -fastopt suffix.
```bash
sbt> fastLinkJS
```
--------------------------------
### Install npm Packages for Chart.js and ScalablyTyped
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/tutorial/scalablytyped.md
Installs Chart.js as a regular dependency and its TypeScript type definitions along with the TypeScript compiler as development dependencies. These are required for ScalablyTyped to generate Scala.js facade types.
```shell
$ npm install -S chart.js@2.9.4
...
$ npm install -D @types/chart.js@2.9.29 typescript@4.9.5
...
```
--------------------------------
### Filtering Undefined/None Values in Arrays
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/sjs-for-js/es6-to-scala-part1.md
Illustrates how to filter out undefined values from a JavaScript array and None values from a Scala array. The JavaScript example uses the filter method with a check for undefined, while the Scala example uses filter with isDefined on Option.
```javascript
const data = [1, 2, 3, undefined, 5, undefined, 7];
const res = data.filter((x) => x !== undefined);
```
--------------------------------
### Scala.js Method Overloading Example
Source: https://github.com/scala-js/scala-js-website/blob/main/doc/interoperability/export-to-javascript.md
Demonstrates how to export multiple Scala methods with the same JavaScript name, allowing for runtime overload resolution based on arguments. Includes examples of successful dispatch and a compile error scenario due to ambiguous overloads.
```scala
class Foo(val x: Int) {
@JSExport
def foobar(): Int = x
@JSExport
def foobar(y: Int): Int = x+y
@JSExport("foobar")
def bar(b: Boolean): Int = if (b) 0 else x
}
```
```javascript
console.log(foo.foobar());
console.log(foo.foobar(5));
console.log(foo.foobar(false));
```
```scala
class Foo(val x: Int) {
@JSExport
def foobar(): Int = x
@JSExport
def foobar(y: Int): Int = x+y
@JSExport("foobar")
def bar(i: Int): Int = if (i == 0) 0 else x
}
```
--------------------------------
### Running SBT with a Specific Scala.js Version
Source: https://github.com/scala-js/scala-js-website/blob/main/_posts/news/2020-02-25-announcing-scalajs-1.0.0.md
These bash commands demonstrate how to start the SBT build process. The first command starts SBT with the default Scala.js version (1.0.0), while the second command explicitly sets the `SCALAJS_VERSION` environment variable to '0.6.32' to use an older version.
```bash
$ sbt
```
```bash
$ SCALAJS_VERSION=0.6.32 sbt
```