PHPToJS
raw JSON → 10.3.0 verified Fri May 01 auth: no javascript maintenance
PHP-to-JavaScript transpiler that converts PHP code into JavaScript code. Version 10.3.0 is the latest stable release, with irregular release cadence. It supports a subset of PHP syntax, including classes, closures, and namespaces, but does not target full PHP compatibility. Key differentiators include the ability to run PHP code in the browser without a server, and integration with the Uniter project. However, it is not actively maintained and has known limitations with newer PHP features.
Common errors
error TypeError: phptojs is not a function ↓
cause In v10, PHPToJS is a class, not a function. Calling it without `new` throws.
fix
Use
const engine = new PHPToJS(); const result = engine.transpile(code); error Cannot find module 'php-parser' ↓
cause Missing optional dependency `php-parser` which is required at runtime.
fix
Run
npm install php-parser alongside phptojs. error Error: Unsupported PHP feature: match expression ↓
cause PHP match expressions (>=8.0) are not supported in the transpiler.
fix
Use
if/elseif or switch statements instead. Warnings
breaking In v10, the default export changed from a function to a class. Use `new PHPToJS()` instead of calling `PHPToJS()` directly. ↓
fix Replace `const result = phptojs(code)` with `const engine = new PHPToJS(); const result = engine.transpile(code)`.
deprecated The `render` method is deprecated in favor of `transpile`. ↓
fix Replace `.render()` with `.transpile()`.
breaking In v9, the library used a synchronous API. v10 changed to asynchronous transpilation for large files. ↓
fix Use `await engine.transpile(code)` or handle promises.
gotcha PHP short echo tags `<?=` are not supported before PHP 7.4. Use `<?php echo` instead. ↓
fix Replace `<?=` with `<?php echo` in your PHP source.
gotcha Namespaces are partially supported; relative imports may fail. ↓
fix Use fully qualified namespaces where possible.
Install
npm install phptojs yarn add phptojs pnpm add phptojs Imports
- PHPToJS wrong
const PHPToJS = require('phptojs').default;correctimport PHPToJS from 'phptojs'; - transpile wrong
const { transpile } = require('phptojs').transpile;correctimport { transpile } from 'phptojs'; - PHPToJSEngine wrong
const PHPToJSEngine = require('phptojs').Engine;correctimport PHPToJSEngine from 'phptojs/lib/Engine';
Quickstart
import PHPToJS from 'phptojs';
const phptojs = new PHPToJS();
const phpCode = `<?php
function hello($name) {
return 'Hello, ' . $name . '!';
}
echo hello('world');
?>`;
const jsCode = phptojs.transpile(phpCode);
console.log(jsCode);