rust-ts-guide
v1.0.0
Published
A complete guide and example for creating Rust-based Node.js native addons with TypeScript support using NAPI-RS
Maintainers
Readme
Rust to Node.js Native Addon Guide
This repository demonstrates how to write a library in Rust, expose it as a Node.js native addon, and prepare it for publishing as an npm package using napi-rs.
🏗️ Project Structure
rust-ts-package/
├── core/ # Your Rust library
│ ├── src/lib.rs # Rust functions exported to Node.js
│ ├── Cargo.toml # Rust dependencies and metadata
│ └── build.rs # NAPI-RS build configuration
├── index.d.ts # Auto-generated TypeScript definitions
├── index.node # Compiled native binary
├── index.js # JavaScript wrapper with proper exports
├── demo.js # JavaScript usage examples
└── package.json # npm package configuration🚀 Quick Start
Prerequisites
- Node.js (v16+)
- Rust (latest stable)
Installation
# Clone the repository
git clone <your-repo-url>
cd rust-ts-package
# Install dependencies
npm install
# Build the native module
npm run buildUsage
TypeScript/JavaScript
const native = require('./index.node');
console.log(native.greet("World")); // "Hello, World!"
console.log(native.addNumbers(5, 3)); // 8
console.log(native.isEven(4)); // true
console.log(native.sumArray([1, 2, 3, 4])); // 10🛠️ Development Scripts
# Build only the Rust native module
npm run build
# Run JavaScript demo
npm run test
# Clean all build artifacts
npm run clean🔍 Type Safety Examples
The package provides full TypeScript type safety:
// ✅ These work with full IntelliSense
native.addNumbers(5, 3);
native.greet("Hello");
native.createPerson("Alice", 30, "[email protected]");
// ❌ These cause TypeScript compile errors
native.addNumbers("5", 3); // Error: string not assignable to number
native.greet(123); // Error: number not assignable to string
native.isEven("hello"); // Error: string not assignable to number🔧 How It Works
- Rust Functions: Written in
core/src/lib.rswith#[napi]attributes - Auto-Generated Types: NAPI-RS automatically generates
index.d.tswith TypeScript definitions - Type Mapping:
String→stringi32,u32,f64→numberbool→booleanVec<T>→Array<T>Option<T>→T | null- Rust structs → TypeScript interfaces
- Build Process:
cargocompiles Rust to.nodebinary, NAPI-RS handles the bindings
📦 Type Mapping Reference
| Rust Type | TypeScript Type | Example |
|-----------|----------------|---------|
| String | string | "hello" |
| i32, u32 | number | 42 |
| f64 | number | 3.14 |
| bool | boolean | true |
| Vec<T> | Array<T> | [1, 2, 3] |
| Option<T> | T \| null | "value" or null |
| struct | interface | { name: "Alice" } |
Playground
- Modify Rust functions in
core/src/lib.rs - Run
npm run buildto recompile - TypeScript definitions are auto-updated
- Test with
npm run test
