Scala.jsを触ってみた
Scala.jsというScalaで記述な可能なAltJSがあったので、興味本意で導入部分だけですが、触ってみました。
導入
早速、Scala.jsの導入を行っていきます。
プロジェクトの作成
activotr new
コマンドでテンプレートからScalaのプロジェクトを作成します。
$ activator new Fetching the latest list of templates... Browse the list of templates: http://typesafe.com/activator/templates Choose from these featured templates or enter a template name: 1) minimal-akka-java-seed 2) minimal-akka-scala-seed 3) minimal-java 4) minimal-scala 5) play-java 6) play-scala (hit tab to see a list of all templates) > 4
sbtの設定
project/plugins.sbt
に以下を追記
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.12")
build.sbt
に以下を追記
enablePlugins(ScalaJSPlugin) name := "Scala.js Tutorial" scalaVersion := "2.11.7" // or any other Scala version >= 2.10.2
Hello Worldを表示するアプリケーションの作成
src/main/scala/com/example/Hello.scala
を作成
package com.example import scala.scalajs.js.JSApp object Hello extends JSApp { def main(): Unit = { println("Hello world") } }
sbt
を起動して上記のファイルを実行してみます。
$ sbt > run [info] Running com.example.Hello Hello world [success] Total time: 6 s, completed 2016/10/03 23:45:15
JavaScriptファイルに変換
fastOptJS
コマンドでScalaのファイルをJavaScriptのファイルに変換します。
> fastOptJS [success] Total time: 2 s, completed 2016/10/03 23:46:46
JavaScriptファイルを読み込む
実際にHTMLを作成して、先ほど生成したJavaScriptファイルを読み込んでみます。
index.html
を以下の内容で作成します。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./target/scala-2.11/scalajs-fastopt.js"></script> </head> <body> <script type="text/javascript"> com.example.TutorialApp().main() </script> </body> </html>
index.html
でブラウザで読み込んでみます。
無事に読み込まれ、コンソール上に"Hello World"と表示されています。
さいごに
正直、型安全をメリットとするならTypeScriptの方で良いなとは思いました。