Using your library - Hello wasm-pack! (original) (raw)

  1. 1. Introduction
  2. 2. Quickstart
  3. 3. Prerequisites
    1. 3.1. npm (optional)
    2. 3.2. considerations
    3. 3.3. Non-rustup setups
  4. 4. Commands
    1. 4.1. new
    2. 4.2. build
    3. 4.3. test
    4. 4.4. pack and publish
    5. 4.5. init (DEPRECATED)
  5. 5. Tutorials
    1. 5.1. Hybrid applications with Webpack
      1. 5.1.1. Getting started
        1. 5.1.2. Using your library
    2. 5.2. npm browser packages
      1. 5.2.1. Getting started
          1. 5.2.1.1. Manual Setup
        1. 5.2.2. Template deep dive
          1. 5.2.2.1. Cargo.toml
            1. 5.2.2.2. src/lib.rs
            2. 5.2.2.3. src/utils.rs
            3. 5.2.2.4. wee_alloc
            4. 5.2.2.5. tests/web.rs
        2. 5.2.3. Building your project
        3. 5.2.4. Testing your project
        4. 5.2.5. Packaging and publishing
        5. 5.2.6. Using your library
  6. 6. Cargo.toml Configuration
  7. 7. Contributing

Hello wasm-pack!

Run The Code From npm

This portion of the tutorial will help you create a Webpack JavaScript project that will run your WebAssembly code in the browser.

Scaffold a JavaScript Project

To scaffold a project that we can use our new package in, we'll use an npm template calledcreate-wasm-app. To use this run this command in a directory different than your Rust project:

npm init wasm-app my-new-wasm-app

Instead of my-new-wasm-app you can choose a different project name. The tool will create a directory with that name.

If we look in that directory, we'll see the following:

The scaffolded project includes an example WebAssembly package, hello-wasm-pack, in yourpackage.json. Go into the package.json file, add your package, and remove thehello-wasm-pack dependency from the "dependencies" section.

Now, open up the index.js file. Replace the hello-wasm-pack in the first line with the name of your package:

import * as wasm from "<your package name>";

wasm.greet();

Run The Project

Before we run our project, we need to make sure we install our dependencies:

npm install

We should be ready to run our project now! To run our project we'll run:

npm start

Then in a web browser navigate to http://localhost:8080 and you should be greeted with an alert box that says "Hello World!".

If you did congrats you've successfully uploaded your first bit of wasm code to npm and used it properly!