Using your library - Hello wasm-pack! (original) (raw)
- 1. Introduction
- 2. Quickstart
- 3. Prerequisites
- 4. Commands
- 5. Tutorials
- 6. Cargo.toml Configuration
- 7. Contributing
Hello wasm-pack!
This portion of the tutorial will help you create a Webpack JavaScript project that will run your WebAssembly code in the browser.
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:
.gitignore
: ignoresnode_modules
LICENSE-APACHE
andLICENSE-MIT
: most Rust projects are licensed this way, so these are included for youREADME.md
: the file you are reading now!index.html
: a bare bones html document that includes the webpack bundleindex.js
: example js file with a comment showing how to import and use a wasm pkgpackage.json
andpackage-lock.json
:- pulls in devDependencies for using webpack:
* webpack
* webpack-cli
* webpack-dev-server - defines a
start
script to runwebpack-dev-server
- pulls in devDependencies for using webpack:
webpack.config.js
: configuration file for bundling your js with webpack Add Your npm Package
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();
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!