Simple JavaScript interpreter for Python built on top of duktape engine without any external dependencies
—
Built-in compilation support for modern JavaScript dialects and preprocessors including CoffeeScript, ES6+ via Babel, TypeScript, JSX, and LESS CSS preprocessing. All transpilers are self-contained with no external dependencies.
Compiles CoffeeScript source code to JavaScript using the built-in CoffeeScript compiler. Supports all standard CoffeeScript language features including classes, comprehensions, and destructuring.
def coffee_compile(source):
"""
Compiles the given source from CoffeeScript to JavaScript.
Parameters:
- source: str - CoffeeScript source code
Returns:
str - Compiled JavaScript code
Raises:
JSRuntimeError: When CoffeeScript compilation fails
"""Usage example:
import dukpy
coffee_code = '''
square = (x) -> x * x
numbers = [1, 2, 3, 4, 5]
squares = (square num for num in numbers)
console.log squares
'''
js_code = dukpy.coffee_compile(coffee_code)
print(js_code)Compiles modern JavaScript (ES6+) to ES5 for broader browser compatibility using BabelJS. Supports extensive configuration through Babel options and plugins.
def babel_compile(source, **kwargs):
"""
Compiles the given source from ES6+ to ES5 using BabelJS.
Parameters:
- source: str - ES6+ JavaScript source code
- **kwargs: Babel compilation options
- presets: list - Babel presets (defaults to ["es2015"])
- plugins: list - Babel plugins
- filename: str - Source filename for debugging
- Other Babel options as documented at http://babeljs.io/docs/usage/options/
Returns:
dict - Compilation result with keys:
- 'code': str - Compiled JavaScript code
- 'map': dict - Source map information
Raises:
JSRuntimeError: When Babel compilation fails
"""Usage example:
import dukpy
# ES6 class compilation
es6_code = '''
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `(${this.x}, ${this.y})`;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
'''
result = dukpy.babel_compile(es6_code)
print(result['code'])
# Custom Babel options
result = dukpy.babel_compile(es6_code, presets=['es2015'], plugins=['transform-runtime'])
print(result['code'])Compiles JSX syntax to React-compatible JavaScript code using Babel with React presets. Automatically configures Babel for JSX transformation.
def jsx_compile(source, **kwargs):
"""
Compiles JSX to React-compatible JavaScript.
Parameters:
- source: str - JSX source code
- **kwargs: Babel compilation options (presets automatically set to ['es2015', 'react'])
- plugins: list - Additional Babel plugins
- filename: str - Source filename for debugging
- Other Babel options
Returns:
str - Compiled JavaScript code (code portion only)
Raises:
JSRuntimeError: When JSX compilation fails
"""Usage example:
import dukpy
jsx_code = '''
const Greeting = ({ name, age }) => {
return (
<div className="greeting">
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<button onClick={() => alert(`Hi ${name}!`)}>
Click me
</button>
</div>
);
};
const App = () => (
<div>
<Greeting name="Alice" age={30} />
<Greeting name="Bob" age={25} />
</div>
);
'''
js_code = dukpy.jsx_compile(jsx_code)
print(js_code)Compiles TypeScript source code to ES5 JavaScript using TypeScript Services. Uses fixed compilation options optimized for SystemJS module format and ES5 target.
def typescript_compile(source):
"""
Compiles the given source from TypeScript to ES5 using TypescriptServices.js.
Parameters:
- source: str - TypeScript source code
Returns:
str - Compiled JavaScript code
Note: Uses fixed compiler options:
- module: SystemJS (requires SystemJS runtime for import statements)
- target: ES5
- newLine: LF
Raises:
JSRuntimeError: When TypeScript compilation fails
"""Usage example:
import dukpy
typescript_code = '''
interface User {
name: string;
age: number;
email?: string;
}
class UserManager {
private users: User[] = [];
addUser(user: User): void {
this.users.push(user);
}
findUser(name: string): User | undefined {
return this.users.find(u => u.name === name);
}
getUserCount(): number {
return this.users.length;
}
}
const manager = new UserManager();
manager.addUser({ name: "Alice", age: 30 });
'''
js_code = dukpy.typescript_compile(typescript_code)
print(js_code)Compiles LESS stylesheets to CSS using the Node.js-compatible LESS compiler. Supports LESS language features including variables, mixins, nesting, and imports.
def less_compile(source, options=None):
"""
Compiles the given source from LESS to CSS.
Parameters:
- source: str - LESS source code
- options: dict, optional - LESS compiler options
- paths: list - Include paths for @import resolution
- Other LESS compiler options
Returns:
str - Compiled CSS code
Raises:
LessCompilerError: When LESS compilation fails
RuntimeError: When compilation results are unavailable
"""Usage example:
import dukpy
less_code = '''
@primary-color: #007bff;
@secondary-color: #6c757d;
@border-radius: 4px;
.button {
background-color: @primary-color;
border: 1px solid darken(@primary-color, 10%);
border-radius: @border-radius;
color: white;
padding: 8px 16px;
&:hover {
background-color: darken(@primary-color, 5%);
}
&.secondary {
background-color: @secondary-color;
border-color: darken(@secondary-color, 10%);
}
}
.card {
border: 1px solid #dee2e6;
border-radius: @border-radius;
.header {
background-color: #f8f9fa;
padding: 12px 16px;
border-bottom: 1px solid #dee2e6;
}
.body {
padding: 16px;
}
}
'''
css_code = dukpy.less_compile(less_code)
print(css_code)
# With custom options
css_code = dukpy.less_compile(less_code, options={
'paths': ['./styles', './node_modules'],
})class LessCompilerError(Exception):
"""
Exception raised when LESS compilation fails.
Contains details about LESS syntax errors, import resolution failures,
and other compilation issues.
"""Error handling example:
import dukpy
try:
# Invalid LESS syntax
css = dukpy.less_compile(".invalid { color: ; }")
except dukpy.LessCompilerError as e:
print(f"LESS compilation error: {e}")
try:
# Missing import
css = dukpy.less_compile('@import "nonexistent.less";')
except dukpy.LessCompilerError as e:
print(f"LESS compilation error: {e}")All transpilers integrate with WebAssets for automated compilation in web applications. See WebAssets for filter configuration and usage.
Install with Tessl CLI
npx tessl i tessl/pypi-dukpy