📋 环境准备

必需依赖

  • Node.js 10+ (推荐 18+)
  • Rust 1.65+ 稳定版
  • npm 或 pnpm/yarn
bash
# 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 验证安装
rustc --version
node --version

🚀 创建项目

bash
# 使用 npm 创建项目
npm init neon@latest my-project

# 进入项目目录
cd my-project

# 安装依赖
npm install

📁 项目结构

text
my-project/
├── lib/
│   └── index.js      # JavaScript 入口
├── native/
│   ├── Cargo.toml    # Rust 配置
│   └── src/
│       └── lib.rs    # Rust 源码
└── package.json

💻 编写代码

Rust 端

rust (native/src/lib.rs)
use neon::prelude::*;

// 简单函数
fn hello(mut cx: FunctionContext) -> JsResult {
    Ok(cx.string("Hello from Rust!"))
}

// 带参数的函数
fn add(mut cx: FunctionContext) -> JsResult {
    let a = cx.argument::(0)?.value(&mut cx);
    let b = cx.argument::(1)?.value(&mut cx);
    Ok(cx.number(a + b))
}

// 导出模块
#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
    cx.export_function("hello", hello)?;
    cx.export_function("add", add)?;
    Ok(())
}

JavaScript 端

javascript (lib/index.js)
const addon = require('../native');

console.log(addon.hello());  // "Hello from Rust!"
console.log(addon.add(1, 2)); // 3

module.exports = addon;

🔧 构建与测试

bash
# 开发模式构建
npm run build

# 运行测试
npm test

# 发布构建
npm run build -- --release

📦 发布到 npm

bash
# 登录 npm
npm login

# 发布
npm publish

Neon 模块作为标准 npm 包发布,用户安装时自动编译原生代码。

⚡ 使用 cargo-cp-artifact

Neon 使用 cargo-cp-artifact 自动化构建:

json (package.json)
{
  "scripts": {
    "build": "cargo-cp-artifact -nc native/index.node -- cargo build --manifest-path native/Cargo.toml --release"
  },
  "devDependencies": {
    "cargo-cp-artifact": "^0.1"
  }
}