在 IntelliJ IDEA 中入门 Kotlin/Wasm
Kotlin/Wasm is an Experimental feature. It may be dropped or changed at any time. It is available only starting with Kotlin 1.8.20.
This tutorial demonstrates how to work with a Kotlin/Wasm application in IntelliJ IDEA.
Before you start
- Download and install the latest version of IntelliJ IDEA.
Clone the Kotlin/Wasm examples repository by selecting File | New | Project from Version Control in IntelliJ IDEA.
You can also clone it from the command line:
git clone [email protected]:Kotlin/kotlin-wasm-examples.git
Run the application
- Open the Gradle tool window: View | Tool Windows | Gradle.
In the kotlin-wasm-browser-example | Tasks | kotlin browser, select and run the wasmJsBrowserRun task.
Alternatively, you can run the following command in Terminal from the project directory:
./gradlew wasmJsBrowserRun -t
Once the application starts, open the following URL in your browser:
http://localhost:8080/
You should see “Hello, World!” text:
Troubleshooting
Despite the fact that most of the browsers support WebAssembly, you need to update the settings in your browser.
To run a Kotlin/Wasm project, you need to update the settings of the target environment:
【Chrome】
For version 109:
Run the application with the
--js-flags=--experimental-wasm-gc
command line argument.For version 110 or later:
- Go to
chrome://flags/#enable-webassembly-garbage-collection
in your browser. - Enable WebAssembly Garbage Collection.
- Relaunch your browser.
- Go to
【Firefox】
For version 109 or later:
- Go to
about:config
in your browser. - Enable
javascript.options.wasm_function_references
andjavascript.options.wasm_gc
options. - Relaunch your browser.
【Edge】
For version 109 or later:
Run the application with the --js-flags=--experimental-wasm-gc
command line argument.
Update your application
Open
Simple.kt
and update the code:import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.dom.appendElement
import kotlinx.dom.appendText
fun main() {
document.body?.appendText("Hello, ${greet()}!")
document.body?.appendElement("button") {
this.textContent = "Click me, I'm a button!"
addEventListener("click") {
window.setTimeout({
window.alert("👋")
null
}, 1000)
}
}
}
fun greet() = "world"
This code adds a button to the document and an action.
Run the application again. Once the application starts, open the following URL in your browser:
http://localhost:8080
You should see the “Hello, World” text within the button:
Click the button to see the alert message:
Now you can work with Kotlin/Wasm code that runs in the browser!
下一步做什么?
Try out other Kotlin/Wasm examples from the kotlin-wasm-examples
repository: