使用 napi-rs 搭建开发环境
4/20/2023, 4:49:00 PM#Napi-RS#Rust
AI Summary
napi-rs 提供了方便的命令来让我们基于 Rust 开发 node 的 addon,farm 也是基于 napi-rs 开发的。本小节记录了 napi-rs 的搭建过程,并添加了调试命令以增强调试体验。详细流程包括初始化项目、使用 pnpm + cargo 将原有项目改造成 monorepo 项目,添加相应的包,生成 binding 文件,以及添加调试功能。最终完成了环境搭建。

napi-rs

https://napi.rs/docs/introduction/getting-started 提供了方便的命令来让我们基于 Rust 开发 node 的 addon,farm 也是基于 napi-rs 开发的,本小节记录 napi-rs 搭建过程,并且添加调试命令 增强调试体验。 详细流程

  1. 初始化项目 https://napi.rs/docs/introduction/getting-started 根据官网步骤初始化项目目录
  2. 使用 pnpm + cargo 将原有项目改造成 monorepo 项目 a. 将原来的 yarn 文件删除 创建 pnpm-workspakce.yaml 然后执行 pnpm install b. 将原来的 rust 项目也改造成 monorepo 的形式 具体配置文件如下

_10
# pnpm-workspace.yaml
_10
packages:
_10
- packages/*
_10
- examples/*
_10
- crates/*


_12
<!-- Cargo.toml -->
_12
[workspace]
_12
members = ["crates/*"]
_12
resolver = "2"
_12
_12
[workspace.dependencies]
_12
napi = {version = "2.15.0", default-features = false, features = [
_12
"napi4",
_12
"error_anyhow",
_12
"serde-json",
_12
]}
_12
napi-derive = "2.15.0"

  1. 添加相应的包

_10
cli
_10
├── Cargo.toml
_10
├── build.rs
_10
└── src
_10
└── lib.rs

具体文件内容


_21
# Cargo.toml
_21
[package]
_21
edition = "2021"
_21
name = "farm_cli"
_21
version = "0.1.0"
_21
_21
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
_21
_21
[lib]
_21
crate-type = ["cdylib"]
_21
_21
[dependencies]
_21
napi = {workspace = true}
_21
napi-derive = {workspace = true}
_21
_21
[build-dependencies]
_21
napi-build = "2.0.1"
_21
_21
[profile.release]
_21
lto = true
_21
strip = "symbols"

build.rs


_14
use napi_build::setup;
_14
_14
fn main() {
_14
setup()
_14
}
_14
#![deny(clippy::all)]
_14
_14
#[macro_use]
_14
extern crate napi_derive;
_14
_14
#[napi]
_14
pub fn sum(a: i32, b: i32) -> i32 {
_14
a + b
_14
}

  1. packages 文件目录

_10
cli
_10
├── binding
_10
│ ├── binding.cjs
_10
│ ├── binding.d.ts
_10
│ └── index.darwin-arm64.node
_10
├── package.json
_10
└── src
_10
└── index.js

如何生成 binding 文件

Note

添加如下的命令


_10
"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


_10
const { sum } = require('../binding/binding.cjs');
_10
const total = sum(1, 2);
_10
console.log(total);

测试执行 输出没有问题


_10
3

添加调试 .vscode 下面添加

launch.json


_14
{
_14
"version": "0.2.0",
_14
"configurations": [
_14
{
_14
"type": "lldb",
_14
"request": "launch",
_14
"sourceLanguages": ["rust"],
_14
"name": "debug rust",
_14
"program": "node",
_14
"preLaunchTask": "npm: build:debug",
_14
"args": ["--inspect", "${file}"]
_14
}
_14
]
_14
}

tasks.json


_12
{
_12
"version": "2.0.0",
_12
"tasks": [
_12
{
_12
"type": "npm",
_12
"script": "build:dev",
_12
"group": "build",
_12
"problemMatcher": [],
_12
"label": "npm: build:debug"
_12
}
_12
]
_12
}

到此环境搭建完毕 代码地址 https://github.com/Maidang1/rust-learn-code/commit/51f5d71cdf9c6a3aa691057523e9145a9bde81af

作者:Madinah