Hello, stdweb!

09 Jan 2018 0 Comments

Lets create primitive cargo project with stdweb library. We'll change only the header on the index page from rust code.

Preparation

Installing cargo-web

cargo install -f cargo-web

Creating project

cargo new hello_stdweb --bin

Adding dependency in cargo.toml

[dependencies]
stdweb = "0.3.0"

Files creation

extern crate stdweb;

use stdweb::web::{
    INode,
    document
};

fn main() {
    stdweb::initialize();

    let header = document().query_selector("h1").unwrap();
    header.set_text_content("Hello, stdweb!");
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello, stdweb!</title>
</head>
<body>
    <h1>Header!</h1>
    <script src="js/app.js"></script>
</body>
</html>

/js/app.js is a wrapper for wasm module.


Running
cargo web start --target-webasm

Output

?[m?[m?[32m?[1m    Finished?[m release [optimized] target(s) in 0.0 secs

If you need to serve any extra files put them in the 'static' directory
in the root of your crate; they will be served alongside your application.
You can also put a 'static' directory in your 'src' directory.

Your application is being served at '/js/app.js'. It will be automatically
rebuilt if you make any changes in your code.

You can access the web server at `http://127.0.0.1:8000`.

Result

Hello, stdweb!


Building
cargo web build --target-webasm

You can find the next generated files:

  • hello_stdweb/target/wasm32-unknown-unknown/release/hello_stdweb.js
  • hello_stdweb/target/wasm32-unknown-unknown/release/hello_stdweb.wasm