napi-rs#
https://napi.rs/docs/introduction/getting-started は、Rust を基に Node のアドオンを開発するための便利なコマンドを提供します。farm も napi-rs を基に開発されており、この小節では napi-rs のセットアッププロセスを記録し、デバッグコマンドを追加してデバッグ体験を強化します。
詳細なプロセス
- プロジェクトの初期化 https://napi.rs/docs/introduction/getting-started に従って公式手順でプロジェクトディレクトリを初期化します。
- pnpm + cargo を使用して既存のプロジェクトを monorepo プロジェクトに変更します。
a. 既存の yarn ファイルを削除し、pnpm-workspace.yaml を作成してから pnpm install を実行します。
b. 既存の Rust プロジェクトも monorepo 形式に変更します。具体的な設定ファイルは以下の通りです。
# pnpm-workspace.yaml
packages:
- packages/*
- examples/*
- crates/*
<!-- Cargo.toml -->
[workspace]
members = ["crates/*"]
resolver = "2"
[workspace.dependencies]
napi = {version = "2.15.0", default-features = false, features = [
"napi4",
"error_anyhow",
"serde-json",
]}
napi-derive = "2.15.0"
- 必要なパッケージを追加します。
cli
├── Cargo.toml
├── build.rs
└── src
└── lib.rs
具体的なファイル内容
# Cargo.toml
[package]
edition = "2021"
name = "farm_cli"
version = "0.1.0"
# 詳細なキーとその定義については https://doc.rust-lang.org/cargo/reference/manifest.html を参照してください。
[lib]
crate-type = ["cdylib"]
[dependencies]
napi = {workspace = true}
napi-derive = {workspace = true}
[build-dependencies]
napi-build = "2.0.1"
[profile.release]
lto = true
strip = "symbols"
build.rs
use napi_build::setup;
fn main() {
setup()
}
#![deny(clippy::all)]
#[macro_use]
extern crate napi_derive;
#[napi]
pub fn sum(a: i32, b: i32) -> i32 {
a + b
}
- packages ファイルディレクトリ
cli
├── binding
│ ├── binding.cjs
│ ├── binding.d.ts
│ └── index.darwin-arm64.node
├── package.json
└── src
└── index.js
binding ファイルを生成する方法
以下のコマンドを追加します。
"build:rs:debug": "napi build --platform --cargo-name farm_cli -p farm_cli --cargo-cwd ../../ binding --js binding.cjs --dts binding.d.ts"
index.cjs
const { sum } = require('../binding/binding.cjs')
const total = sum(1,2);
console.log(total)
テスト実行 出力に問題はありません。
デバッグを追加
.vscode の下に追加します。
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"sourceLanguages": ["rust"],
"name": "debug rust",
"program": "node",
"preLaunchTask": "npm: build:debug",
"args": ["--inspect", "${file}"]
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "build:dev",
"group": "build",
"problemMatcher": [],
"label": "npm: build:debug"
}
]
}
デバッグの効果
これで環境のセットアップが完了しました。
コードのアドレス https://github.com/Maidang1/rust-learn-code/commit/51f5d71cdf9c6a3aa691057523e9145a9bde81af