snowpack-plugin-wasm-pack

Snowpack plugin for rust using wasm-pack 🦀

Usage no npm install needed!

<script type="module">
  import snowpackPluginWasmPack from 'https://cdn.skypack.dev/snowpack-plugin-wasm-pack';
</script>

README

snowpack-plugin-wasm-pack

Snowpack plugin for rust using wasm-pack 🦀

Installation

yarn add --dev snowpack-plugin-wasm-pack

The plugin also depends on wasm-pack and cargo-watch

These can be installed with:

cargo install wasm-pack

(or following these instructions)

cargo install cargo-watch

Usage

Create a new RustWasm project within your project:

wasm-pack new <name>

Add the plugin to your Snowpack config:

snowpack.config.js

module.exports = {
  plugins: [
    [
      'snowpack-plugin-wasm-pack',
      {
        projectPath: './path/to/project',
      },
    ],
  ],
};

Options

Name Description Type Required Default
projectPath Relative path from the root to your wasm-pack project. string yes -
outDir Directory for the compiled assets. string "pkg"
outName Sets the prefix for output file names. string "index"
logLevel Sets the log level of wasm-pack. "info" or "warn" or "error" "warn"
scope Scope of your package name, eg: @test/my-great-wasm. string -
profile Wasm-pack build profile "dev" or "release" or "profiling" see below
extraArgs Any extra args you want to pass to wasm-pack. eg: --no-typescript. Array<string> -
wasmPackPath Path to a custom install of wasm-pack. string -

The default value of profile is "dev" if the Snowpack config is in "development" mode or "release" if not.

In your code:

wasm-pack exports an init funtion as the default export. This must be called (once) before any other functions can be used. snowpack-plugin-wasm-pack will automatically configure path aliases to your project under the name of your package:

project/lib.rs

// --- code omitted

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

src/index.ts

import init, { add } from 'project-name';

const maths = async () => {
  await init();

  console.log('Addition in rust:', add(1, 2));
};

Usage with typescript

You need to manually add the alias to your tsconfig under compilerOptions -> paths.

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "project-name": ["./path/to/project/pkg"]
    }
  }
}

Multiple RustWasm projects

Add the plugin multiple times for multiple projects:

snowpack.config.js

module.exports = {
  plugins: [
    [
      'snowpack-plugin-wasm-pack',
      {
        projectPath: './path/to/project',
      },
    ],
    [
      'snowpack-plugin-wasm-pack',
      {
        projectPath: './path/to/another/project',
      },
    ],
  ],
};

Useful links:

wasm-pack wasm-bindgen snowpack