├── build.sbt
├── index.html
├── node_modules
│ └── scalajs-loader
│ ├── LICENSE
│ ├── README.md
│ ├── index.js
│ └── package.json
├── package.json
├── project
│ ├── build.properties
│ └── plugins.sbt
├── src
│ └── main
│ └── scala
│ └── test
│ └── App.scala
└── webpack.config.js
1. 环境配置
1.1 安装sbt
brew install sbt
1.2 全局安装webpack
npm i -g webpack
1.3 新建工程目录,并使用npm初始化
mkdir test-scalajs \
&& cd test-scalajs \
&& npm init -f
1.4. 配置scala.js
(1)./build.sbt
enablePlugins(ScalaJSPlugin)
name := "test-scalajs"
scalaVersion := "2.12.2" // or any other Scala version >= 2.10.2
// This is an application with a main method
scalaJSUseMainModuleInitializer := true
注:
./build.sbt
的name
很重要,决定了编译后的文件名,test-scalajs-fastopt.js,
位于./target/scala-2.12/test-scalajs-fastopt.js
。
它应该与项目的文件名称保持一致,scalajs-loader才能找到编译后的js文件。
(2)./project/plugins.sbt
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.19")
(3)./project/build.properties
sbt.version=0.13.15
1.5. 配置webpack
新建./webpack.config.js
,并写入如下内容,
const path = require('path');
module.exports = {
context: path.resolve(__dirname, ''),
entry: [
path.resolve(__dirname, 'src/main/scala/test/App.scala')
],
output: {
path: path.resolve(__dirname, 'dist/'),
filename: 'app.js'
},
module: {
loaders: [
{
test: /\.scala$/,
loader: 'scalajs-loader'
}
]
}
};
注:
这里我们先配置entry
,随后再添加入口文件,
src/main/scala/test/App.scala
。
1.6 安装scalajs-loader
npm i --save-dev scalajs-loader
2. 添加功能代码
2.1 新建./src/main/scala/test/App.scala
package test
object App {
def main(args: Array[String]): Unit = {
println("Hello world!")
}
}
2.2 新建./index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Scala.js Tutorial</title>
</head>
<body>
<!-- Include Scala.js compiled code -->
<script type="text/javascript" src="./dist/app.js"></script>
</body>
</html>
3. 编译和运行
3.1 使用webpack编译并打包
webpack --watch
3.2 浏览器打开./index.html
打开控制台,显示
Hello world!
4. 操作DOM
4.1 修改./build.sbt
在./build.sbt
尾部添加,
libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.1"
4.2 修改./src/main/scala/test/App.scala
package test
import org.scalajs.dom
import dom.document
object App {
def appendPar(targetNode: dom.Node, text: String): Unit = {
val parNode = document.createElement("p")
val textNode = document.createTextNode(text)
parNode.appendChild(textNode)
targetNode.appendChild(parNode)
}
def main(args: Array[String]): Unit = {
appendPar(document.body, "Hello World")
}
}
4.2 重新编译运行
打开./index.html,页面显示Hello World
。