nativejs-compiler

raw JSON →
2.0.0 verified Fri May 01 auth: no javascript

nativejs-compiler (also known as hardware.js) is a JavaScript/TypeScript to C transpiler that converts JS/TS code into readable C89 code for low-power microcontrollers and IoT devices. Current version 2.0.0 (released July 2024) supports approximately 50% of ES3 syntax, targeting environments with very limited memory (512 bytes to 120KB RAM). Key differentiators include generating minimal, readable C code without unnecessary overhead, and employing escape analysis for memory management. It supports basic ES3 features like var, if-else, loops, functions, arrays, strings, and some built-in objects, but notably lacks support for float numbers, `this`, `new`, and `typeof`. Releases are occasional, focused on incremental feature coverage. Compared to other JS-to-C transpilers, it prioritizes output readability and small footprint over full language support.

error Error: Cannot find module 'nativejs-compiler'
cause Package is not installed or wrong package name used.
fix
Run npm install nativejs-compiler and ensure the package name is 'nativejs-compiler'.
error TypeError: nativejs_compiler_1.transpile is not a function
cause Using CommonJS require instead of ESM import.
fix
Use import { transpile } from 'nativejs-compiler' instead of const { transpile } = require('nativejs-compiler').
error Unsupported feature: This expression (this)
cause The `this` keyword is not supported by the transpiler.
fix
Remove usage of this or refactor code to use explicit parameters.
breaking ESM-only since v2.0.0: The package no longer supports CommonJS require() syntax.
fix Use import syntax instead of require().
deprecated The `transpile` function is deprecated in favor of `compile`; `transpile` may be removed in v3.0.0.
fix Replace transpile() with compile().
gotcha Float numbers are not supported; using them will cause compile-time errors or incorrect output.
fix Use integer values only, or check if float support is added in future versions.
gotcha The `this` keyword is not supported; transpiling code that relies on `this` will fail.
fix Avoid using `this` or rewrite code to pass context explicitly.
gotcha Only about 50% of ES3 features are implemented; using unsupported syntax will cause transpilation errors.
fix Refer to COVERAGE.md in the GitHub repo for the current list of supported features.
npm install nativejs-compiler
yarn add nativejs-compiler
pnpm add nativejs-compiler

Transpiles a simple JavaScript 'Hello world' console.log to C code using the transpile function.

import { transpile } from 'nativejs-compiler';
const jsCode = `console.log("Hello world!");`;
const cCode = transpile(jsCode);
console.log(cCode);
// Output:
// #include <stdio.h>
// int main() {
//     printf("Hello world!\n");
//     return 0;
// }