50 lines
1.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 使用 wasm-pack
---
这个工具由 Rust / Wasm 工作组开发维护,并且是现在最为活跃的 WebAssembly 应用开发工具。 它支持将代码打包成 `npm` 模块,并且随附了 [Webpack 插件](https://github.com/wasm-tool/wasm-pack-plugin),可以轻松的与已有的 JavaScript 应用结合。可以点击[这里](https://drager.github.io/wasm-pack/book/introduction.html)了解更多。
:::note
注:如果使用 `wasm-pack`作为开发工具,`Cargo.toml` 中的 `crate-type` 需要指定为 `cdylib`
```toml
[lib]
crate-type = ["rlib", "cdylib"]
```
:::
## 安装
```bash
cargo install wasm-pack
```
## 构建
这条命令将在工程根目录下的 `./pkg` 目录中生成打包后的应用,其中包含应用的 WebAssembly 文件以及用来启动应用的 JavaScript 包装器。
```bash
wasm-pack build --target web
```
## 打包
关于 Rollup 的更多信息,请查看这篇[指南](https://rollupjs.org/guide/en/#quick-start)
```bash
rollup ./main.js --format iife --file ./pkg/bundle.js
```
当使用诸如 rollup.js 打包时,你可以省去 `--target web`。
## 部署
选取你喜爱的服务器。这里我们使用一个简单的 Python 服务器来部署项目
```bash
python -m http.server 8000
```
如果您没有安装 Python您可以安装并使用[`simple-http-server`](https://github.com/TheWaWaR/simple-http-server) crate 作为替代。