LoginSignup
1
3

More than 3 years have passed since last update.

Rust で wasm-pack するときの準備

Posted at

概要

wasm 関係の記事を書くときにいちいち準備から書きたくないのでまとめました。

wasm-pack をインストール

※cargoが必要です

$ cargo install wasm-pack

クレートを作成

クレートを作成し、そのディレクトリに移動します。

$ cargo new --lib [クレート名]
$ cd [クレート名]

この時点でのディレクトリ構成(一部省略):

[クレート名]
 ├cargo.toml
 └src
  └lib.rs

webpack 等のインストール

※npmが必要です
※yarn等を使う場合は適宜読み替えてください

絶対に必要ではありませんが、動作確認などで使います。
すでにサーバーがあるなら、webpack-dev-server はお好みで。

$ npm init
$ npm install -D @wasm-tool/wasm-pack-plugin html-webpack-plugin webpack webpack-cli webpack-dev-server

この時点でのディレクトリ構成(一部省略):

[クレート名]
 ├cargo.toml
 ├package.json
 ├package-lock.json
 └src
  └lib.rs

webpack.config.js の作成

クレートのルートディレクトリに webpack.config.js というファイルを作り、以下のように記述します。

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");

module.exports = {
    resolve: {
        extensions: [".js"]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, "./src/index.html")
        }),
        new WasmPackPlugin({
            crateDirectory: path.join(__dirname, "./")
        })
    ]
};

この時点でのディレクトリ構成(一部省略):

[クレート名]
 ├cargo.toml
 ├package.json
 ├package-lock.json
 ├webpack.config.js
 └src
  └lib.rs

その他、必要なファイルの作成

[クレート名]/src に index.js と index.html を作成し、それぞれ以下のように記述します。

index.js:

import("../pkg");

index.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
</head>

<body>
    <div id="app"></div>
</body>

</html>

この時点でのディレクトリ構成(一部省略):

[クレート名]
 ├cargo.toml
 ├package.json
 ├package-lock.json
 ├webpack.config.js
 └src
  ├index.html
  ├index.js
  └lib.rs

その他、設定の作成

package.json の scripts"start": "./node_modules/.bin/webpack-dev-server" を追加します。

この時点での package.json の例:

{
  "name": "[クレート名]",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "./node_modules/.bin/webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@wasm-tool/wasm-pack-plugin": "^1.0.1",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.39.3",
    "webpack-cli": "^3.3.8",
    "webpack-dev-server": "^3.8.0"
  }
}

cargo.toml の編集

各記事の内容に従ってください。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3