ts2php
raw JSON → 0.30.3 verified Fri May 01 auth: no javascript maintenance
ts2php is a TypeScript to PHP transpiler (v0.30.3, latest release Jan 2021) that converts TypeScript/JavaScript code into PHP. It aims to enable code sharing between front-end and back-end by translating TypeScript into PHP. Key differentiators: it supports a large subset of TypeScript features including classes, interfaces, generics, async/await, and standard library polyfills. It is read-only (not a bidirectional bridge) and generates PHP code that can be used in any PHP project. Releases have slowed, indicating maintenance mode. Requires TypeScript ^3.7.0 as a peer dependency.
Common errors
error TypeError: ts2php is not a function ↓
cause Using require() on an ESM-only export in Node.js CJS context.
fix
Use ESM import: import ts2php from 'ts2php';
error Cannot find module 'typescript' ↓
cause Missing TypeScript peer dependency.
fix
Install typescript: npm install typescript@^3.7.0
error Error: Supplied options.modules is not supported ↓
cause Invalid modules option passed to transpile().
fix
Use valid modules option: 'commonjs' or 'esm' (not 'amd' or 'system').
Warnings
breaking Requires TypeScript >= 3.7.0 as peer dependency. Older TypeScript versions are incompatible. ↓
fix Install TypeScript 3.7.0 or later: npm install typescript@^3.7.0
gotcha Do not use require() in Node.js CJS context; use ESM import or call the module with a different syntax. ↓
fix Use ESM imports: import ts2php from 'ts2php';
deprecated The compile() function was renamed to transpile() in v0.28. ↓
fix Use transpile() instead.
Install
npm install ts2php yarn add ts2php pnpm add ts2php Imports
- default wrong
const ts2php = require('ts2php')correctimport ts2php from 'ts2php' - transpile wrong
const { transpile } = require('ts2php');correctimport { transpile } from 'ts2php' - CompileOptions wrong
import { CompileOptions } from 'ts2php'correctimport type { CompileOptions } from 'ts2php'
Quickstart
import ts2php from 'ts2php';
const code = `
function add(a: number, b: number): number {
return a + b;
}
`;
const result = ts2php(code, {
declare: true,
});
console.log(result);
// Output: PHP source code with declared types if enabled.